How to create UIImage with vertical gradient using “from-color” and “to-color”

后端 未结 9 642
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-04 00:09

How to create new image just with gradient colors, using \"from-color\" and \"to-color\"?

9条回答
  •  滥情空心
    2021-01-04 00:48

    A simpler answer, using a CAGradientLayer.

    CGSize size = CGSizeMake(width, height);
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.frame = CGRectMake(0, 0, size.width, size.height);
    layer.colors = @[(__bridge id)[UIColor blackColor].CGColor,  // start color
                     (__bridge id)[UIColor whiteColor].CGColor]; // end color
    
    UIGraphicsBeginImageContext(size);
    @try {
      [layer renderInContext:UIGraphicsGetCurrentContext()];
      UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    } @finally {
      UIGraphicsEndImageContext();
    }
    

提交回复
热议问题