UILabel text color based on custom linear gradient

后端 未结 2 445
灰色年华
灰色年华 2021-01-03 04:14

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?

相关标签:
2条回答
  • 2021-01-03 04:36

    You might want to use one of these customizable labels:

    • FXLabel
    • LEffectLabel
    • THLabel
    0 讨论(0)
  • 2021-01-03 04:36

    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.

    0 讨论(0)
提交回复
热议问题