ios - 如何在iOS中创建从全色到不透明度为0的渐变?
问题描述
我看过这里,但根据他们的例子,我试过并在下面展示,没有用。它无法完成以下任务。我正在寻找从全黑到不透明度为 0 的全黑的渐变:
@IBDesignable
final class GradientView: UIView {
@IBInspectable var startColor: UIColor = UIColor.clear
@IBInspectable var endColor: UIColor = UIColor.clear
override func draw(_ rect: CGRect) {
let gradient: CAGradientLayer = CAGradientLayer()
// gradient.frame = bounds
gradient.frame = CGRect(x: CGFloat(0),
y: CGFloat(0),
width: superview!.frame.size.width,
height: superview!.frame.size.height)
gradient.colors = [startColor.cgColor, endColor.cgColor]
gradient.zPosition = -1
layer.addSublayer(gradient)
}
}
我怎样才能做到这一点,最好是在界面构建器中?
解决方案
以下是我的实现
@IBDesignable
final class GradientView: UIView {
override func draw(_ rect: CGRect) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Gradient Declarations
let gradient = CGGradient(colorsSpace: nil, colors: [UIColor.white.cgColor,
UIColor.white.blended(withFraction: 0.5, of: UIColor.black).cgColor,
UIColor.black.cgColor] as CFArray, locations: [0, 0.51, 0.89])!
//// Rectangle Drawing
let rectangleRect = CGRect(x: frame.minX + 11, y: frame.minY + 8, width: 85, height: 54)
let rectanglePath = UIBezierPath(rect: rectangleRect)
context.saveGState()
rectanglePath.addClip()
context.drawLinearGradient(gradient,
start: CGPoint(x: rectangleRect.midX, y: rectangleRect.minY),
end: CGPoint(x: rectangleRect.midX, y: rectangleRect.maxY),
options: [])
context.restoreGState()
}
}
推荐阅读
- linux - 跳过获取配置文件'main/binary-i386/Packages'
- amazon-web-services - 如何在 AWS 上运行单次运行的非联网/非扩展 docker 应用程序
- javascript - 如何解决 Uncaught SyntaxError: Unexpected token < in JSON at position 0 console 错误?
- vue.js - v-cards 从顶部开始而不是垂直居中(Vuetify)
- erd - Common Data Model 中的 ERD 文件 - 如何打开?欧文/PowerDesigner?
- node.js - MeteorJS Mup 部署:挂在“node-pre-gyp WARN 使用 node-pre-gyp https 下载请求”
- amazon-web-services - AWS Managed Airflow - 如何在触发长时间运行的 lambda 时解决 350 秒超时
- python-3.x - 为什么记录器级别始终为零?我怎样才能得到真正的水平?
- javascript - 浏览器抛出 TypeError:无法读取未定义的属性“地图”
- eclipse - 导入源代码:无法安装 Gradle 发行版