【问题标题】:NSGradient drawInBezierPath iOS equivalentNSGradient drawInBezierPath iOS 等效
【发布时间】:2013-05-21 16:13:45
【问题描述】:

是否有相当于 - (void)drawInBezierPath:(NSBezierPath *)path angle:(CGFloat)angle 的 iOS 版本?

我需要在 UIBezierPath 内绘制一个渐变,但无法让它工作。渐变在整个屏幕上绘制。

【问题讨论】:

  • 在上下文中设置剪切路径,然后绘制渐变。 (参见CGContextAddPath,CGContextClip)

标签: ios gradient


【解决方案1】:

此示例在 Swift 3 中的 UIBezierPath 内创建渐变。它使用绿色/白色渐变绘制斜线。

import UIKit

class DrawingView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isOpaque = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }


    override func draw(_ rect: CGRect) {
        let startPoint = CGPoint(x:100, y:100)
        let endPoint = CGPoint(x: 300, y:400)

        let context = UIGraphicsGetCurrentContext()!
        context.setStrokeColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0);
        // create a line
        context.move(to: startPoint)
        context.addLine(to: endPoint)
        context.setLineWidth(4)
        // use the line created above as a clipping mask
        context.replacePathWithStrokedPath()
        context.clip()

        // create a gradient
        let locations: [CGFloat] = [ 0.0, 0.5 ]

        let colors = [UIColor.green.cgColor,
                      UIColor.white.cgColor]

        let colorspace = CGColorSpaceCreateDeviceRGB()

        let gradient = CGGradient(colorsSpace: colorspace,
                                  colors: colors as CFArray, locations: locations)

        let gradientStartPoint = CGPoint(x: rect.midX, y: rect.minY)
        let gradientEndPoint = CGPoint(x: rect.midX, y: rect.maxY)

        context.drawLinearGradient(gradient!,
                                    start: gradientStartPoint, end: gradientEndPoint,
                                    options: .drawsBeforeStartLocation)
        UIGraphicsEndImageContext()
    }

}

【讨论】:

    猜你喜欢
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    相关资源
    最近更新 更多