ios - 如何向 UIView 添加径向渐变?

标签 ios objective-c uiview radial-gradients

我有一个 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: Custom Class

第三步

在 Attributes Inspector 中为渐变设置 Inside Color 和 Outside Color,然后在 Storyboard 上查看变化: Radial Gradient

(注意:我把 Storyboard 上的 UIView 做得足够大,所以它填满了整个

关于ios - 如何向 UIView 添加径向渐变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8125623/

相关文章:

ios - 在长 NSString 中添加新行/换行符/段落

ios - 如何识别 UIView subview 上的触摸

iphone - 更改 UIVIEW 的变换/旋转/缩放而不使用动画

UIScrollView 中的 iOS 编程缩放不起作用

ios - 仅为 10-20 个最终用户轻松分发 iOS 应用程序

objective-c - 从相册/UIimagepickercontroller 获取电影的创建日期

iphone - 使用简单音频引擎的声音循环之间的轻微停顿

ios - 是否可以通过在 iOS swift 中画线来对图像进行分组?

ios - 如何解码光盘上应用程序文档文件夹的模拟器路径?

ios - iOS 7 中的 UI 状态栏改变颜色