需求:传入颜色数组、图片宽高、行列数,生成像素图片。
生成的图片
/// 生成随机颜色
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)!
}
}
// 传一个颜色数组
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 与行列数的关系
extension UIImage {
/// 根据传入的颜色数组生成对应像素图
/// - Parameters:
/// - colors: 颜色数组
/// - size: 生成的 UIImage 大小
/// - col: 列
/// - row: 行
/// - haveline: 是否绘制分割线,默认不绘
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
}
}