我有一个 UIView
,我想要它有一个径向渐变,我想知道如何去做?
最佳答案
swift 3 - @IBDesignable
我计算出了 Karlis 和 Alexander 的答案。我的目标是尽可能简化。例如删除颜色空间和位置 (nil
),以便渐变使用默认值。
如何使用
第一步
创建文件并添加以下代码: 导入 UIKit
@IBDesignable
class RadialGradientView: UIView {
@IBInspectable var InsideColor: UIColor = UIColor.clear
@IBInspectable var OutsideColor: UIColor = UIColor.clear
override func draw(_ rect: CGRect) {
let colors = [InsideColor.cgColor, OutsideColor.cgColor] as CFArray
let endRadius = min(frame.width, frame.height) / 2
let center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2)
let gradient = CGGradient(colorsSpace: nil, colors: colors, locations: nil)
UIGraphicsGetCurrentContext()!.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: endRadius, options: CGGradientDrawingOptions.drawsBeforeStartLocation)
}
}
第二步
在 Storyboard 上,在 Identity Inspector 中将 UIView 设置为上面的 RadialGradientView
:
第三步
在 Attributes Inspector 中为渐变设置 Inside Color 和 Outside Color,然后在 Storyboard 上查看变化:
(注意:我把 Storyboard 上的 UIView 做得足够大,所以它填满了整个
关于ios - 如何向 UIView 添加径向渐变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8125623/