我正在尝试在运行时生成具有渐变颜色背景(从纯色到透明)的 View 。有办法吗?
最佳答案
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 :
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 到 change direction of gradient .
如果有任何其他 View 添加到此 UIView
(例如 UILabel
),您可能需要考虑设置这些 UIView< 的背景颜色
到 [UIColor clearColor]
,因此呈现渐变 View 而不是 subview 的背景颜色。使用 clearColor
会对性能造成轻微影响。
关于ios - 以编程方式创建具有颜色渐变的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23074539/