简体   繁体   中英

How to make rounded corners in image that was drawn with BezierPath

I have a tableView cell, that has an image view. For this view I created UIImage extension, where I am drawing with bezierPath 2 rectangle, and then, from this drawing I make an image.

 class func drawTwoRectangles(_ frameOne: CGRect, frameTwo: CGRect, frameColor: UIColor) -> UIImage {

    UIGraphicsBeginImageContext(CGSize(width: frameOne.size.width, height: frameOne.size.height))
    let context = UIGraphicsGetCurrentContext()

    UIColor(red: 0/255.0, green: 153/255.0, blue: 216/255.0, alpha: 1.0).setFill()

    let bpath:UIBezierPath = UIBezierPath(roundedRect:CGRect(origin: CGPoint(x:1, y:1), size: CGSize(width: frameOne.size.width - 2, height: frameOne.size.height - 2)), byRoundingCorners: [.allCorners], cornerRadii: CGSize(width: 5, height: 5))
    bpath.lineCapStyle = .round
    bpath.lineJoinStyle = .round

    bpath.close()
    bpath.fill()


    UIColor.white.setFill()
    UIColor.white.setStroke()

    let bpathTwo:UIBezierPath = UIBezierPath(rect: frameTwo)
    bpathTwo.close()
    bpathTwo.fill()
    bpathTwo.stroke()

    frameColor.setStroke()

    let bpathThree:UIBezierPath = UIBezierPath(roundedRect: CGRect(origin: CGPoint(x:1, y:1), size: CGSize(width: frameOne.size.width - 2, height: frameOne.size.height - 2)), cornerRadius: 5)
    bpathThree.lineWidth = 2
    bpathThree.close()

    bpathThree.stroke()

    bpath.append(bpathTwo)
    bpath.append(bpathThree)

    context?.addPath(bpath.cgPath)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image!
}

So when I set this image into an Image view, corners are not smooth, they are blurred: 在此处输入图片说明

Could you please advice, how to deal with it? thanks in advance!

Try to replace this:

UIGraphicsBeginImageContext(CGSize(width: frameOne.size.width, height: frameOne.size.height))

with this:

UIGraphicsBeginImageContextWithOptions(frameOne.size, false, UIScreen.main.scale)

By the way, you can pass 0.0 as third parameter, according to documentation :

The scale factor to apply to the bitmap. If you specify a value of 0.0, the scale factor is set to the scale factor of the device's main screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM