Melany
Melany

Reputation: 466

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:enter image description here

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

Upvotes: 1

Views: 81

Answers (1)

alexburtnik
alexburtnik

Reputation: 7741

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.

Upvotes: 1

Related Questions