Core Graphics Circular Image Blurry

江枫思渺然 提交于 2019-12-10 10:23:33

问题


I'm drawing a circle image using core graphics with a modified implementation of this SO answer

Here's my source:

+ (UIImage*)circularImageWithRadius:(CGFloat)radius color:(UIColor*)color{
    CGRect rect = CGRectMake(0.0f, 0.0f, radius*2, radius*2);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillEllipseInRect(context, rect);
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

The edges are blurry and I'm not sure why (I thought it didn't matter what resolution the device was, it would work right out of the box).

I tried replacing CGContextFillEllipseInRect(context, rect); with CGContextFillRect(context, rect); and that was blurry too. Then I tried CGContextFillRect(context, CGRectMake(0, 0, radius*4, radius*4) and it works perfectly, sharp image and everything (albeit being a a square, not a circle). So I changed back to CGContextDrawEllipseInRect(context, CGRectMake(0, 0, radius*4, radius*4) but this was my result:

whereas with the rectangle, it was the same size as when using radius*2 but with a much sharper image.

How can I fix my blurry issue and why does CGContextFillEllipseInRect not fill the pre-defined image rect?


回答1:


I feel dumb for having found this immediately after I posted but this answer pointed the way.

I just added

if(UIGraphicsBeginImageContextWithOptions != NULL) {
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
} else {
    UIGraphicsBeginImageContext(rect.size);
}

instead of just UIGraphicsBeginImageContext(rect.size); into my original source and it's crystal clear and sharp.




回答2:


For Swift 3.0

        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        defer { UIGraphicsEndImageContext() }
        if let context = UIGraphicsGetCurrentContext() {
            /// Do Stuff
        }


来源:https://stackoverflow.com/questions/21108504/core-graphics-circular-image-blurry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!