在iOS上繪制漸變,我們創建一個對象,但這一過程是通過調用Core Graphics C函數來完成的。
這裡不是將路徑對象提供給漸變,並讓漸變來繪制自己,而是對當前圖形上下文進行修剪(clip),然後從屏幕上的一點向另一個點繪制漸變。“修剪”是指將繪制范圍局限於一個形狀,這樣可以防止漸變充滿整個視圖。
此外,除了提供一個應當據以繪制漸變的角度之外,還應當傳送漸變的起始繪制坐標,此坐標應當轉換為視圖的坐標控件。
下面是在playground中的實現代碼:
//: Playground - noun: a place where people can play import UIKit class MyView : UIView{ override func drawRect(rect: CGRect) { let colorSpace = CGColorSpaceCreateDeviceRGB() let context = UIGraphicsGetCurrentContext() let gradientStartColor = UIColor(red: 0.1, green: 0.1, blue: 0.8, alpha: 1) let gradientEndColor = UIColor(red: 1, green: 0.6, blue: 0.8, alpha: 1) let gradientcolors : CFArray = [gradientStartColor.CGColor,gradientEndColor.CGColor] let gradientLocations : [CGFloat] = [0.0,1.0] let gradient = CGGradientCreateWithColors(colorSpace, gradientcolors, gradientLocations) let pathRect = CGRectInset(self.bounds, 20, 20) let topPoint = CGPointMake(self.bounds.size.width/2, 20) let bottomPoint = CGPointMake(self.bounds.size.width/2 , self.bounds.size.height-20) let roundedRectanglePath = UIBezierPath(roundedRect: pathRect,cornerRadius: 4) CGContextSaveGState(context) roundedRectanglePath.addClip() CGContextDrawLinearGradient(context, gradient, bottomPoint, topPoint, .DrawsAfterEndLocation) CGContextRestoreGState(context) } } let viewRect = CGRect(x: 0, y: 0, width: 100, height: 100) let myEmptyView = MyView(frame:viewRect) myEmptyView.backgroundColor = UIColor.clearColor()
下面是效果圖