以编程方式创建具有颜色渐变的 UIView [英] Programmatically create a UIView with color gradient
本文介绍了以编程方式创建具有颜色渐变的 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:
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];
斯威夫特:
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屋!
查看全文