我正在尝试在 iOS 上创建带圆角的缩略图,并在图像底部添加一个横条。
我有以下代码:
extension UIImage {
func thumbnails(with options: SomeDrawingOptions) -> UIImage? {
// ...
UIGraphicsBeginImageContextWithOptions(targetRect.size, false, 0)
defer {
UIGraphicsEndImageContext()
}
let context = UIGraphicsGetCurrentContext()!
UIColor.white.setFill()
context.fill(targetRect)
UIBezierPath(roundedRect: targetRect, cornerRadius: 8).addClip()
// Drawing image
draw(in: targetRect)
// Drawing a transparent mask
UIColor.black.withAlphaComponent(0.4).setFill()
context.fill(targetRect)
// Drawing bar
UIColor.white.setFill()
context.fill(someBarRect)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
最后,我得到了一张带有尖锐圆角的图像,就像下面的快照中那样。
有什么消除圆角锯齿的建议吗?
======= 添加了解决方案 ======
感谢@wj2061 的解答,问题解决。这是代码:
extension UIImage {
func thumbnails(with options: SomeDrawingOptions) -> UIImage? {
// ...
let targetRect = options.targetRect
let clippedPath = UIBezierPath(roundedRect: targetRect, cornerRadius: 8)
func makeImage() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(targetRect.size, false, 0)
defer { UIGraphicsEndImageContext() }
let context = UIGraphicsGetCurrentContext()!
draw(in: targetRect)
// Drawing a transparent mask
UIColor.black.withAlphaComponent(0.4).setFill()
context.fill(targetRect)
// Drawing bar
UIColor.white.setFill()
context.fill(someBarRect)
return UIGraphicsGetImageFromCurrentContext()
}
UIGraphicsBeginImageContextWithOptions(targetRect.size, false, 0)
defer { UIGraphicsEndImageContext() }
let context = UIGraphicsGetCurrentContext()!
// Drawing image
clippedPath.addClip()
makeImage()?.draw(in: targetRect)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
最佳答案
所以这个陷阱似乎与 UIBezierPath(roundedRect: targetRect, cornerRadius: 8).addClip()
有关,我尝试在步骤 1 中为图像添加蒙版,添加角到步骤2中的image,代码是这样的
extension UIImage {
func thumbnails() -> UIImage? {
let targetRect = CGRect(x: 0, y: 0, width: 100, height: 150)
UIGraphicsBeginImageContextWithOptions(targetRect.size, false, 0)
defer {
UIGraphicsEndImageContext()
}
UIBezierPath(roundedRect: targetRect, cornerRadius: 8).addClip()
let makedImage = self.makedImage()
makedImage?.draw(in : targetRect)
return UIGraphicsGetImageFromCurrentImageContext()
}
func makedImage()->UIImage?{
let targetRect = CGRect(x: 0, y: 0, width: 100, height: 150)
let someBarRect = CGRect(x: 0, y: 100, width: 100, height: 50)
UIGraphicsBeginImageContextWithOptions(targetRect.size, false, 0)
defer {
UIGraphicsEndImageContext()
}
let context = UIGraphicsGetCurrentContext()!
draw(in : targetRect)
// Drawing a transparent mask
UIColor.black.withAlphaComponent(0.4).setFill()
context.fill(targetRect)
// Drawing bar
UIColor.white.withAlphaComponent(1).setFill()
context.fill(someBarRect)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
关于ios - 在 iOS 上绘制圆角图像时遇到奇怪的锯齿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41050939/