作者:Arthur Knopper初斑,原文鏈接舀寓,原文日期:2016-10-18
譯者:冬瓜蔗候;校對:星夜暮晨垒酬;定稿:CMB
Core Graphics 是一套非常強(qiáng)大的底層 API 接口集合。在這篇教程中淑蔚,我們將借助 Core Graphics 來創(chuàng)建漸變顏色。出于簡便起見愕撰,我們將創(chuàng)建線性漸變 (linear gradients)刹衫。所謂線性漸變,是從一個點到另外一個點顏色過渡的描述搞挣。我們將會創(chuàng)建一個從左向右漸變的視圖带迟。該教程的實驗環(huán)境是 Xcode 8 和 iOS 10。
首先打開 Xcode 創(chuàng)建一個 Single View Application囱桨。
點擊 Next仓犬。輸入 product name,填寫 IOS10DrawGradientsTutorial 然后將 Organization Name 和 Organization Identifier 這兩項按照你的習(xí)慣來填寫舍肠。將 Language 設(shè)置為 Swift 搀继,并且確定 Devices 選項為 iPhone窘面。
在我們的工程中添加一個新文件。選擇 iOS->Source->Cocoa Touch Class叽躯。將新的 Class 命名為 GradientView 并且確定其繼承自 UIView 類财边。
轉(zhuǎn)到 storyboard 中,在 Document Outline 選擇要編輯的視圖点骑,然后點擊 Identity Inspector 選項卡酣难,在 Custom Class 一欄中將 Class 選擇 GradientView 。

打開文件 gradientView.swift
黑滴,并修改 drawRect
方法:
override func draw(_ rect: CGRect) {
// 1
guard let currentContext = UIGraphicsGetCurrentContext() else { return }
// 2
currentContext.saveGState()
// 3
let colorSpace = CGColorSpaceCreateDeviceRGB()
// 4
let startColor = UIColor.red
guard let startColorComponents = startColor.cgColor.components else { return }
let endColor = UIColor.blue
guard let endColorComponents = endColor.cgColor.components else { return }
// 5
let colorComponents: [CGFloat]
= [startColorComponents[0], startColorComponents[1], startColorComponents[2], startColorComponents[3], endColorComponents[0], endColorComponents[1], endColorComponents[2], endColorComponents[3]]
// 6
let locations:[CGFloat] = [0.0, 1.0]
// 7
guard let gradient = CGGradient(colorSpace: colorSpace,colorComponents: colorComponents,locations: locations,count: 2) else { return }
let startPoint = CGPoint(x: 0, y: self.bounds.height)
let endPoint = CGPoint(x: self.bounds.width,y: self.bounds.height)
// 8
currentContext.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: UInt32(0)))
// 9
currentContext.restoreGState()
}
-
UIGraphicsGetCurrentContext
得到了圖形上下文 (graphical context)憨募,這里可以當(dāng)做一個新的畫布。 - 圖形上下文將被存儲袁辈,以便于之后的存儲操作馋嗜。
-
CGColorSpace
描述的是顏色的域值范圍。大多情況下你會使用到 RGB 模式來描述顏色吵瞻。 - 這里我們定義一個漸變樣式的起始顏色和結(jié)束顏色葛菇。
CGColor
對象是底層顏色接口的定義。這個接口方法會從CGColor
中獲取指定顏色橡羞。 - 在這個數(shù)組中眯停,將 RGB 顏色分量和 alpha 值寫入。
- 在此處可以定義各種顏色的相對位置卿泽。
-
CGGradient
用來描述漸變信息莺债。 - 這里漸變將沿縱軸 (vertical axis) 方向繪制。
- 存儲圖形上下文签夭。
編譯并運行我們的工程:
可以從我的 Github 上下載本篇文章的示例代碼齐邦。
本文由 SwiftGG 翻譯組翻譯,已經(jīng)獲得作者翻譯授權(quán)第租,最新文章請訪問 http://swift.gg措拇。