Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel text color based on custom linear gradient

So I want to set the text color for a UILabel based on a gradient made in photoshop. I have the rgb values for the gradient, {211,119,95} and {199,86,56}. Is this possible? How can I do it?

like image 626
Carmichael Avatar asked Apr 09 '13 14:04

Carmichael


2 Answers

Another way if you want to target iOS 6+, with a category to UIColor

You create a UIColor from a gradient:

+ (UIColor*) gradientFromColor:(UIColor*)c1 toColor:(UIColor*)c2 withHeight:(int)height
{
  CGSize size = CGSizeMake(1, height);
  UIGraphicsBeginImageContextWithOptions(size, NO, 0);
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();

  NSArray* colors = [NSArray arrayWithObjects:(id)c1.CGColor, (id)c2.CGColor, nil];
  CGGradientRef gradient = CGGradientCreateWithColors(colorspace, (CFArrayRef)colors, NULL);
  CGContextDrawLinearGradient(context, gradient, CGPointMake(0, 0), CGPointMake(0, size.height), 0);

  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

  CGGradientRelease(gradient);
  CGColorSpaceRelease(colorspace);
  UIGraphicsEndImageContext();

  return [UIColor colorWithPatternImage:image];
}

Then with attrString as your NSMutableAttributeString:

[attrString addAttribute:NSForegroundColorAttributeName value:[UIColor gradientFromColor:[UIColor greenColor] toColor:[UIColor redColor] withHeight:labelView.height] range:defaultRange];
labelView.attributedString = attrString;

or simply set the textColor if you don't also need strokes or other styling effect

labelView.textColor = [UIColor gradientFromColor:[UIColor greenColor] toColor:[UIColor redColor] withHeight:labelView.height];

And voila, it works better with UILabel over one line, otherwise you have to calculate your line height from your font (UIFont.leading) and pass it to the method, the background will repeat vertically.

like image 74
rnaud Avatar answered Sep 28 '22 19:09

rnaud


You might want to use one of these customizable labels:

  • FXLabel
  • LEffectLabel
  • THLabel
like image 42
Felix Avatar answered Sep 28 '22 17:09

Felix