Search code examples
iosuicolorcagradientlayer

Set a gradient background color bug for UILabel


I have generated the gradient UIColor through the following code:

CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor,
                     (__bridge id)[UIColor yellowColor].CGColor,
                     (__bridge id)[UIColor blueColor].CGColor];
gradientLayer.locations = @[@0.3, @0.5, @1.0];
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1.0, 0);
gradientLayer.frame = CGRectMake(0, 0, 300, 100);
UIGraphicsBeginImageContextWithOptions(gradientLayer.bounds.size,NO, [UIScreen mainScreen].scale);
[gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIColor *gradientColor = [UIColor colorWithPatternImage:gradientImage];

To verify the UIColor, I added the following code:

UIView *view = [[UIView alloc]initWithFrame:CGRectMake(20, 130, 300, 100)];
[view setBackgroundColor:gradientColor];
[self.view addSubview:view];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 240, 300, 100)];
[label setBackgroundColor:gradientColor];
[self.view addSubview:label];

I found that on the UIView, the color is normal, the UILabel, the color gets smallerAs shown:

I wonder why? Is there a solution? Thanks.


Solution

  • There are lots of other ways to do this. colorWithPatternImage is always pretty skanky; why don't you use a CAGradientLayer? That's what it's for, after all. Or, since you know the view works the way you want, why not make the label's background color clear, and put the gradient view behind it?