我使用drawInRect()方法绘制图像我的矩形大小为120*120,我的图像是100*100我如何在swift中为我的图像设置背景颜色
dim*_*iax 17
如果您需要绘制图像的背景,出于优化和装饰的目的,您可以通过特定方式绘制图像:
UIImage(named: "someImage")?.withBackground(color: .white)
extension UIImage {
func withBackground(color: UIColor, opaque: Bool = true) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
guard let ctx = UIGraphicsGetCurrentContext(), let image = cgImage else { return self }
defer { UIGraphicsEndImageContext() }
let rect = CGRect(origin: .zero, size: size)
ctx.setFillColor(color.cgColor)
ctx.fill(rect)
ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height))
ctx.draw(image, in: rect)
return UIGraphicsGetImageFromCurrentImageContext() ?? self
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用此扩展程序:
extension UIImage {
func imageWithColor(tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context = UIGraphicsGetCurrentContext()!
context.translateBy(x: 0, y: self.size.height)
context.scaleBy(x: 1.0, y: -1.0);
context.setBlendMode(.normal)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect
context.clip(to: rect, mask: self.cgImage!)
tintColor.setFill()
context.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
}
Run Code Online (Sandbox Code Playgroud)
然后
image.imageWithColor("#1A6BAE".UIColor)
Run Code Online (Sandbox Code Playgroud)
更新了@ Egghead的Swift 3解决方案
extension UIImage {
static func imageWithColor(tintColor: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
tintColor.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
UIImage.imageWithColor(tintColor: <Custom color>)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26521 次 |
| 最近记录: |