ios - 以编程方式创建具有颜色渐变的 UIView

标签 ios uiview uicolor

我正在尝试在运行时生成具有渐变颜色背景(从纯色到透明)的 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/

相关文章:

javascript - 2D 游戏的最佳 HTML5/Javascript 引擎?

ios - IOS程序如何关闭后台模式的音乐?

ios - 核心数据精确存储 NSDecimalNumber

ios - 如何获取UIScrollView中显示区域的中心?

ios - 找出 UIView 进入(滚动到)屏幕的时刻

swift - 以某种方式将自定义 .colorNames 添加到 UIColor 中?

ios - 如何在单元格部分而不是标题部分设置背景颜色?

objective-c - 从 .plist 文件存储和获取 UIColor

iphone - CoreData - 关系的一侧始终为零

ios - 使 UIView 固定位置到 UITableViewController 的顶部