Home > Software engineering >  Why draw(in: CGRect) draws border around ellipse when it should not?
Why draw(in: CGRect) draws border around ellipse when it should not?

Time:08-13

This is my simple function I use for drawing an image in context:

let renderer=UIGraphicsImageRenderer(size: CGSize(width: 330, height: 330))
let img=renderer.image{ ctx in
    let circle=CGRect(x:0,y:0,width: 330, height: 330)
    ctx.cgContext.setFillColor(UIColor.white.cgColor)
    ctx.cgContext.addEllipse(in: circle)
    ctx.cgContext.drawPath(using: .fill)
                
    let image = UIImage(named: "1")!
    image.draw(in: CGRect(x: 80, y: 80, width: 100, height: 100))
}

And the result is following:

enter image description here

As you can see there is output of UIGraphicsImageRenderer with border around ellipse. Why? Border is not defined anywhere, but it is printed.

The image named 1 is the following one:

enter image description here

NOTE:

This issue appears only when compiling ios app. Using playground everything is fine and ok.

CodePudding user response:

OK, the updated code still does not match.

First, in your posted image, the background is not white.

Second, even accounting for that, there is no "edge" on the rendered UIImage.

So, I'm going to make a guess here....

Assuming you execute the img = renderer.image { .... code block, and then you set imageView.image = img, my suspicion is that you have something like this:

imageView.backgroundColor = .lightGray
imageView.layer.cornerRadius = imageView.frame.height / 2.0

So, the lightGray "circle" is the lightGray background anti-aliased to the .cornerRadius.

I would be that if set:

imageView.backgroundColor = .clear

and do not set the layer's cornerRadius (no need to), your ellipse border will be gone.

If it's still there, then you need to provide some code that actually reproduces the issue.

CodePudding user response:

If you only want to fill the path, and not draw it, use fillPath rather than drawPath.


FWIW, you could also just bypass the CoreGraphics context and just fill the oval directly

let image = renderer.image { _ in
    UIColor.white.setFill()
    UIBezierPath(ovalIn: CGRect(x:0, y:0, width: 330, height: 330))
        .fill()
                
    let image = UIImage(named: "1")!
    image.draw(in: CGRect(x: 80, y: 80, width: 100, height: 100))
}
  • Related