2017-07-17 173 views
2

這是我必須創建一個gradiated三角形的代碼(三角形的,而不是平坦的顏色,有一種顏色漸變):如何創建gradiated三角形圖像

extension UIImage { 

    struct GradientPoint { 
     var location: CGFloat 
     var color: UIColor 
    } 

    static func gradiatedTriangle(side: CGFloat)->UIImage { 

     UIGraphicsBeginImageContextWithOptions(CGSize(width: side, height: side), false, 0) 
     let ctx = UIGraphicsGetCurrentContext()! 
     ctx.saveGState() 

     //create gradient and draw it 
     let gradientPoints = [UIImage.GradientPoint(location: 0, color: UIColor.from(rgb: 0xff0000)), UIImage.GradientPoint(location: 1, color: UIColor.from(rgb: 0xd0d0d0))] 
     let gradient = CGGradient(colorSpace: CGColorSpaceCreateDeviceRGB(), colorComponents: gradientPoints.flatMap{$0.color.cgColor.components}.flatMap{$0}, locations: gradientPoints.map{$0.location}, count: gradientPoints.count)! 
     ctx.drawLinearGradient(gradient, start: CGPoint.zero, end: CGPoint(x: 0, y: side), options: CGGradientDrawingOptions()) 

     //draw triangle 
     ctx.beginPath() 
     ctx.move(to: CGPoint(x: side/2, y: side)) 
     ctx.addLine(to: CGPoint(x: 0, y: 0)) 
     ctx.addLine(to: CGPoint(x: side, y: 0)) 
     ctx.closePath() 
     ctx.drawPath(using: .fill) 

     ctx.restoreGState() 
     let img = UIGraphicsGetImageFromCurrentImageContext()! 
     UIGraphicsEndImageContext() 

     return img 
    } 
} 

然而,返回的圖像在背景中有一個方形漸變,頂部有一個黑色三角形。我可以使填充清晰,但我不知道如何修剪路徑周圍的漸變層,以便只保留三角形。如何修剪掉我繪製的路徑之外的漸變圖層?

回答

2

與此一替換你的代碼,首先你需要添加的路徑,然後ctx.clip()剪輯的背景,然後繪製你的梯度

import UIKit 

extension UIImage { 

    struct GradientPoint { 
     var location: CGFloat 
     var color: UIColor 
    } 

    static func gradiatedTriangle(side: CGFloat)->UIImage { 

     UIGraphicsBeginImageContextWithOptions(CGSize(width: side, height: side), false, 0) 
     let ctx = UIGraphicsGetCurrentContext()! 

     //draw triangle 
     ctx.beginPath() 
     ctx.move(to: CGPoint(x: side/2, y: side)) 
     ctx.addLine(to: CGPoint(x: 0, y: 0)) 
     ctx.addLine(to: CGPoint(x: side, y: 0)) 
     ctx.closePath() 
     ctx.clip() 

     //create gradient and draw it 
     let gradientPoints = [UIImage.GradientPoint(location: 0, color: UIColor.red), UIImage.GradientPoint(location: 1, color: UIColor.blue)] 
     let gradient = CGGradient(colorSpace: CGColorSpaceCreateDeviceRGB(), colorComponents: gradientPoints.flatMap{$0.color.cgColor.components}.flatMap{$0}, locations: gradientPoints.map{$0.location}, count: gradientPoints.count)! 
     ctx.drawLinearGradient(gradient, start: CGPoint.zero, end: CGPoint(x: 0, y: side), options: CGGradientDrawingOptions()) 


     let img = UIGraphicsGetImageFromCurrentImageContext()! 
     UIGraphicsEndImageContext() 

     return img 
    } 
} 

結果

enter image description here

希望這有助於你,最好的問候