Carmichael
Carmichael

Reputation: 467

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?

Upvotes: 5

Views: 7434

Answers (2)

rnaud
rnaud

Reputation: 2622

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.

Upvotes: 13

Felix
Felix

Reputation: 35384

You might want to use one of these customizable labels:

Upvotes: 2

Related Questions