UILabel文本颜色基于自定义线性渐变

Car*_*ael 5 iphone gradient colors uilabel

所以我想根据photoshop中的渐变设置UILabel的文本颜色.我有梯度的rgb值,{211,119,95}和{199,86,56}.这可能吗?我该怎么做?

rna*_*aud 13

另一种方法,如果你想要目标iOS 6+,与UIColor类别

您可以从渐变创建UIColor:

+ (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];
}
Run Code Online (Sandbox Code Playgroud)

然后使用attrString作为NSMutableAttributeString:

[attrString addAttribute:NSForegroundColorAttributeName value:[UIColor gradientFromColor:[UIColor greenColor] toColor:[UIColor redColor] withHeight:labelView.height] range:defaultRange];
labelView.attributedString = attrString;
Run Code Online (Sandbox Code Playgroud)

或者只是设置textColor,如果你不需要笔画或其他样式效果

labelView.textColor = [UIColor gradientFromColor:[UIColor greenColor] toColor:[UIColor redColor] withHeight:labelView.height];
Run Code Online (Sandbox Code Playgroud)

瞧,UILabel在一行上效果更好,否则你必须从你的字体(UIFont.leading)计算你的行高并将它传递给方法,背景将垂直重复.


Fel*_*lix 2

您可能想要使用以下可自定义标签之一: