2013-05-21 22 views
2

是否有相當於- (void)drawInBezierPath:(NSBezierPath *)path angle:(CGFloat)angle的iOS?NSGradient drawInBezierPath iOS等效

我需要在UIBezierPath中繪製漸變,並且無法使其工作。漸變繪製在屏幕上。

+3

在您的上下文中設置剪切路徑,然後繪製您的漸變。 (參考CGContextAddPath,CGContextClip) – nielsbot

回答

0

本示例在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() 
    } 

}