以编程方式创建具有颜色渐变的UIView [英] Programmatically create a UIView with color gradient

查看:121
本文介绍了以编程方式创建具有颜色渐变的UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在运行时生成具有渐变颜色背景(纯色到透明)的视图。有没有办法做到这一点?

I'm trying to generate a view with a gradient color background (A solid color to transparent) at runtime. Is there a way of doing that?

推荐答案

Objective-C:



Objective-C:

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
CAGradientLayer *gradient = [CAGradientLayer layer];

gradient.frame = view.bounds;
gradient.colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor blackColor].CGColor];

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



Swift:



Swift:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
let gradient = CAGradientLayer()

gradient.frame = view.bounds
gradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]

view.layer.insertSublayer(gradient, at: 0)

信息使用startPoint和endPoint 改变渐变方向

如果有任何其他视图添加到此 UIView (例如 UILabel ),您可能需要考虑设置 UIView 到 [UIColor clearColor] 因此显示渐变视图而不是子视图的背景颜色。使用 clearColor 会略微降低性能。

If there are any other views added onto this UIView (such as a UILabel), you may want to consider setting the background color of those UIView’s to [UIColor clearColor] so the gradient view is presented instead of the background color for sub views. Using clearColor has a slight performance hit.

这篇关于以编程方式创建具有颜色渐变的UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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