UILabel text color based on custom linear gradient

孤人 提交于 2019-11-29 22:44:43

问题


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?


回答1:


You might want to use one of these customizable labels:

  • FXLabel
  • LEffectLabel
  • THLabel



回答2:


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.



来源:https://stackoverflow.com/questions/15904908/uilabel-text-color-based-on-custom-linear-gradient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!