在iOS上绘制圆角图像时遇到奇怪的锯齿

时间:2016-12-08 23:56:38

标签: ios swift cgcontext quartz-2d

我正在尝试创建带圆角的缩略图,并在iOS的图像底部添加一个条形图。

我有以下代码:

java -jar jacoco-0.8.1/lib/jacococli.jar report jacoco.exec --classfiles directory_with_classes --html directory_for_report

最后,我得到了一个带有尖角圆角的图像,就像下面的快照一样。

Sharp Rounded Corners

有否建议消除圆角的锯齿?

=======添加了解决方案======

感谢@ wj2061的回答,问题解决了。这是代码:

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()
  }
}

1 个答案:

答案 0 :(得分:2)

所以看起来这个陷阱与UIBezierPath(roundedRect: targetRect, cornerRadius: 8).addClip()有关,我尝试在步骤1中为图像添加遮罩,在步骤2中为图像添加角落。代码就像这样

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()
 }
}