Common gradient logic
var beginR : CGFloat = 0.endR : CGFloat = 0.beginG : CGFloat = 0.endG : CGFloat = 0.beginB : CGFloat = 0.endB : CGFloat = 0
/ / for RGB
beginColor.getRed(&beginR, green: &beginG, blue: &beginB, alpha: nil)
endColor.getRed(&endR, green: &endG, blue: &endB, alpha: nil)
func byRow(direction: DrawDirection){
var arrayRows : [Int] = []
for row inminY.. <maxY { arrayRows.append(row) }if direction == .up{
arrayRows = arrayRows.reversed()
}
let deltaR = (endR - beginR) / CGFloat(maxY - minY)
let deltaG = (endG - beginG) / CGFloat(maxY - minY)
let deltaB = (endB - beginB) / CGFloat(maxY - minY)
var offset:CGFloat = 0
for row in arrayRows{
let color = UIColor.init(red: beginR+deltaR*offset, green: beginG+deltaG*offset, blue: beginB+deltaB*offset, alpha: 1)
// context? .setFillColor(color.cgColor)
// context? .fill(CGRect(x: minX, y: row, width: maxX-minX, height: 1))context? .setStrokeColor(color.cgColor) context? .move(to: CGPoint(x: CGFloat(minX),y: CGFloat(row) + 0.5)) // Add 0.5 so that the line is drawn right on the rowcontext? .addLine(to: CGPoint(x: CGFloat(maxX),y: CGFloat(row) + 0.5) ) context? .strokePath() offset +=1}}Copy the code
2. Gradient logic based on hue
var beginHue: CGFloat = 0.endHue: CGFloat = 0.beginBrightness:CGFloat=0.endBrightness:CGFloat = 0
var beginSaturation:CGFloat=0.endSaturation: CGFloat = 0
// Get chroma and brightness
beginColor.getHue(&beginHue, saturation: &beginSaturation, brightness: &beginBrightness, alpha: nil)
endColor.getHue(&endHue, saturation: &endSaturation, brightness: &endBrightness, alpha: nil)
func byCol(direction: DrawDirection){
var arrayCols : [Int] = []
for col inminX.. <maxX { arrayCols.append(col) }if direction == .left{
arrayCols = arrayCols.reversed()
}
let deltaHue = (endHue - beginHue) / CGFloat(maxX - minX)
var offset:CGFloat = 0
for col in arrayCols{
let color = UIColor.init(hue: beginHue+deltaHue*offset, saturation: beginSaturation+deltaHue*offset, brightness: beginBrightness+deltaHue*offset, alpha: 1)
// context? .setFillColor(color.cgColor)
// context? .fill(CGRect(x: minX, y: row, width: maxX-minX, height: 1))context? .setStrokeColor(color.cgColor) context? .move(to: CGPoint(x: CGFloat(col) +0.5.y: CGFloat(minY))) // Add 0.5 so that the line is drawn right on the rowcontext? .addLine(to: CGPoint(x:CGFloat(col) +0.5.y: CGFloat(maxY))) context? .strokePath() offset +=1}}Copy the code