需求:傳入顏色數(shù)組、圖片寬高送爸、行列數(shù),生成像素圖片暖释。
生成的圖片
/// 生成隨機(jī)顏色
extension UIColor {
static var random: Color {
let red = Int.random(in: 0...255)
let green = Int.random(in: 0...255)
let blue = Int.random(in: 0...255)
return Color(red: red, green: green, blue: blue)!
}
}
// 傳一個(gè)顏色數(shù)組
let column: Int = 3
let row: Int = 2
let scale: CGFloat = 100
var randomColors: [UIColor] = []
for _ in 0..<column * row {
randomColors.append(UIColor.random)
}
imageView.image = UIImage.pixelImage(with: randomColors,
size: CGSize(width: CGFloat(column) * scale, height: CGFloat(row) * scale),
col: column, row: row)
lazy var imageView: UIImageView = {
let iv = UIImageView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
view.addSubview(iv)
return iv
}()
用 UIGraphics 繪制袭厂,注意 size 與行列數(shù)的關(guān)系
extension UIImage {
/// 根據(jù)傳入的顏色數(shù)組生成對應(yīng)像素圖
/// - Parameters:
/// - colors: 顏色數(shù)組
/// - size: 生成的 UIImage 大小
/// - col: 列
/// - row: 行
/// - haveline: 是否繪制分割線,默認(rèn)不繪
static func pixelImage(with colors: [UIColor], size: CGSize, column: Int, row: Int, haveline: Bool = false) -> UIImage {
var i = UIImage()
if size.width == 0 || size.height == 0 {
return i
}
if colors.count != column * row {
return i
}
let allRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(allRect.size, false, 0.0)
let context = UIGraphicsGetCurrentContext()!
let signleWidth: CGFloat = size.width / CGFloat(column)
let signleHeight: CGFloat = size.height / CGFloat(row)
var x: CGFloat = 0
var y: CGFloat = 0
var index = 0
for _ in 0..<row {
for _ in 0..<column {
let rect = CGRect(x: x, y: y, width: signleWidth, height: signleHeight)
context.setFillColor(colors[index].cgColor)
context.fill(rect)
index += 1
x += signleWidth
}
x = 0
y += signleHeight
}
if haveline {
let path = CGMutablePath()
for i in 0...row {
path.move(to: CGPoint(x: 0, y: signleHeight * CGFloat(i)))
path.addLine(to: CGPoint(x: size.width, y: signleHeight * CGFloat(i)))
}
for i in 0...column {
path.move(to: CGPoint(x: signleWidth * CGFloat(i), y: 0))
path.addLine(to: CGPoint(x: signleWidth * CGFloat(i), y: size.height))
}
context.addPath(path)
context.setStrokeColor(UIColor.hex(0x999999).cgColor)
context.setLineWidth(0.2)
context.strokePath()
}
i = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
return i
}
}