在UIView上使用CAGradientLayer绘制渐变不起作用 [英] Drawing gradient using CAGradientLayer on UIView not working

查看:89
本文介绍了在UIView上使用CAGradientLayer绘制渐变不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用View Controller的背景视图绘制渐变,但是由于某种原因,我无法使其正常工作.

I'm trying to draw a gradient on the background view of a View Controller with but for some reason I couldn't get it to work.

这是我的方法,从viewDidLoad调用:

Here is my method, which is called from viewDidLoad:

- (void)drawGradient
{
  CAGradientLayer *gradient = [CAGradientLayer layer];
  gradient.frame = self.view.bounds;

  gradient.colors = @[[UIColor greenColor], [UIColor redColor]];
  gradient.locations = @[@0.0, @1.0];

  [self.view.layer insertSublayer:gradient atIndex:0];
}

...但是什么也没有发生,并且没有出现渐变. 我在做什么错了?

...but nothing happens, and the gradient doesn't appear. What am I doing wrong?

推荐答案

感谢Larme的评论,我发现了我的错误.

Thanks to Larme's comment, I figured out my mistake.

代替

gradient.colors = @[[UIColor greenColor], [UIColor redColor]];

这是右边

gradient.colors = @[(id)[UIColor greenColor].CGColor, (id)[UIColor redColor].CGColor];

因为gradient.colors期望NSArrayCGColorRef.为了创建NSArray,还需要(id)强制转换.

Because gradient.colors expects a NSArray of CGColorRef. The (id) cast is also needed in order to create the NSArray.

这篇关于在UIView上使用CAGradientLayer绘制渐变不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆