具有透明圆角的 UIImage

发布于 2024-10-16 00:07:36 字数 3202 浏览 1 评论 0原文

我使用以下代码向 UIImage 添加圆角,但问题是圆角显示“白色”区域而不是透明或“透明”区域。我在这里做错了什么:

- (UIImage *)makeRoundCornerImageWithCornerWidth:(int)cornerWidth cornerHeight:(int)cornerHeight {
    UIImage * newImage = nil;

    if (self != nil)    {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        int w = self.size.width;
        int h = self.size.height;

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);

        CGContextBeginPath(context);
        CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
        [self addRoundedRectToPath:context rect:rect width:cornerWidth height:cornerHeight];

        CGContextClosePath(context);
        CGContextClip(context);

        CGContextDrawImage(context, CGRectMake(0, 0, w, h), self.CGImage);
        CGImageRef imageMasked = CGBitmapContextCreateImage(context);
        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);

        newImage = [[UIImage imageWithCGImage:imageMasked] retain];
        CGImageRelease(imageMasked);

        [pool release];
    }

    return [newImage autorelease];
}


- (void)addRoundedRectToPath:(CGContextRef)context rect:(CGRect)rect width:(float)ovalWidth height:(float)ovalHeight {
    float fw, fh;

    // If the width or height of the corner oval is zero, then it reduces to a right angle,
    // so instead of a rounded rectangle we have an ordinary one.
    if (ovalWidth == 0 || ovalHeight == 0) {
        CGContextAddRect(context, rect);
        return;
    }

    //  Save the context's state so that the translate and scale can be undone with a call
    //  to CGContextRestoreGState.
    CGContextSaveGState(context);

    //  Translate the origin of the contex to the lower left corner of the rectangle.
    CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));

    //Normalize the scale of the context so that the width and height of the arcs are 1.0
    CGContextScaleCTM (context, ovalWidth, ovalHeight);

    // Calculate the width and height of the rectangle in the new coordinate system.
    fw = CGRectGetWidth (rect) / ovalWidth;
    fh = CGRectGetHeight (rect) / ovalHeight;

    // CGContextAddArcToPoint adds an arc of a circle to the context's path (creating the rounded
    // corners).  It also adds a line from the path's last point to the begining of the arc, making
    // the sides of the rectangle.
    CGContextMoveToPoint(context, fw, fh/2);                // Start at lower right corner
    CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);   // Top right corner
    CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);     // Top left corner
    CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);      // Lower left corner
    CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);    // Back to lower right

    // Close the path
    CGContextClosePath(context);

    // Restore the context's state. This removes the translation and scaling
    // but leaves the path, since the path is not part of the graphics state.
    CGContextRestoreGState(context);
}

I'm using following code to add rounded corners to my UIImage, but the problem is that the rounded corners are showing "white" area instead of transparent or "clear". What am i doing wrong here:

- (UIImage *)makeRoundCornerImageWithCornerWidth:(int)cornerWidth cornerHeight:(int)cornerHeight {
    UIImage * newImage = nil;

    if (self != nil)    {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        int w = self.size.width;
        int h = self.size.height;

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);

        CGContextBeginPath(context);
        CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
        [self addRoundedRectToPath:context rect:rect width:cornerWidth height:cornerHeight];

        CGContextClosePath(context);
        CGContextClip(context);

        CGContextDrawImage(context, CGRectMake(0, 0, w, h), self.CGImage);
        CGImageRef imageMasked = CGBitmapContextCreateImage(context);
        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);

        newImage = [[UIImage imageWithCGImage:imageMasked] retain];
        CGImageRelease(imageMasked);

        [pool release];
    }

    return [newImage autorelease];
}


- (void)addRoundedRectToPath:(CGContextRef)context rect:(CGRect)rect width:(float)ovalWidth height:(float)ovalHeight {
    float fw, fh;

    // If the width or height of the corner oval is zero, then it reduces to a right angle,
    // so instead of a rounded rectangle we have an ordinary one.
    if (ovalWidth == 0 || ovalHeight == 0) {
        CGContextAddRect(context, rect);
        return;
    }

    //  Save the context's state so that the translate and scale can be undone with a call
    //  to CGContextRestoreGState.
    CGContextSaveGState(context);

    //  Translate the origin of the contex to the lower left corner of the rectangle.
    CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));

    //Normalize the scale of the context so that the width and height of the arcs are 1.0
    CGContextScaleCTM (context, ovalWidth, ovalHeight);

    // Calculate the width and height of the rectangle in the new coordinate system.
    fw = CGRectGetWidth (rect) / ovalWidth;
    fh = CGRectGetHeight (rect) / ovalHeight;

    // CGContextAddArcToPoint adds an arc of a circle to the context's path (creating the rounded
    // corners).  It also adds a line from the path's last point to the begining of the arc, making
    // the sides of the rectangle.
    CGContextMoveToPoint(context, fw, fh/2);                // Start at lower right corner
    CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);   // Top right corner
    CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);     // Top left corner
    CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);      // Lower left corner
    CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);    // Back to lower right

    // Close the path
    CGContextClosePath(context);

    // Restore the context's state. This removes the translation and scaling
    // but leaves the path, since the path is not part of the graphics state.
    CGContextRestoreGState(context);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

尾戒 2024-10-23 00:07:36

下面是使用 UIKit 调用的更简单的公式:

- (UIImage*) roundCorneredImage: (UIImage*) orig radius:(CGFloat) r {
    UIGraphicsBeginImageContextWithOptions(orig.size, NO, 0);
    [[UIBezierPath bezierPathWithRoundedRect:(CGRect){CGPointZero, orig.size} 
                                cornerRadius:r] addClip];
    [orig drawInRect:(CGRect){CGPointZero, orig.size}];
    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

注意 NO 参数 - 这使得图像上下文透明,因此剪裁的区域是透明的。

Here's a simpler formulation using UIKit calls:

- (UIImage*) roundCorneredImage: (UIImage*) orig radius:(CGFloat) r {
    UIGraphicsBeginImageContextWithOptions(orig.size, NO, 0);
    [[UIBezierPath bezierPathWithRoundedRect:(CGRect){CGPointZero, orig.size} 
                                cornerRadius:r] addClip];
    [orig drawInRect:(CGRect){CGPointZero, orig.size}];
    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

Notice the NO parameter - this makes the image context transparent, so the clipped-out region is transparent.

猫瑾少女 2024-10-23 00:07:36

https://github.com/detroit-labs/AmazeKit

听起来像是图书馆的工作

https://github.com/detroit-labs/AmazeKit

sounds like a job for a library

眼睛会笑 2024-10-23 00:07:36

创建位图上下文后立即使用以下命令清除它:

CGContextClearRect (context, CGRectMake(0, 0, w, h));

Right after creating the bitmap context clear it with:

CGContextClearRect (context, CGRectMake(0, 0, w, h));
天涯沦落人 2024-10-23 00:07:36

卢基亚在你的问题下面的评论是你可能想做的。

确保导入 QuartzCore:

#import <QuartzCore/QuartzCore.h>

然后,如果您有一个想要具有圆角的图像的 UIImageView,只需调用(假设 imageView 是一个属性,cornerRadius 是所需的圆角半径):

self.imageView.layer.cornerRadius = cornerRadius;
self.imageView.clipsToBounds = YES;

由于您已经有了 self.CGImage,所以您可以这样做来创建 UIImageView:

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithCGImage:self.CGImage]];

只需确保在将 imageView 添加为子视图后释放它即可。

lukya's comment below your question is what you probably want to do.

Make sure you import QuartzCore:

#import <QuartzCore/QuartzCore.h>

Then, if you have a UIImageView of your image that you want to have rounded corners, just call (assuming imageView is a property and cornerRadius is the desired corner radius):

self.imageView.layer.cornerRadius = cornerRadius;
self.imageView.clipsToBounds = YES;

Since you already have self.CGImage, you could do this to create a UIImageView:

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithCGImage:self.CGImage]];

Just make sure to release the imageView after you add it as a subview.

谈场末日恋爱 2024-10-23 00:07:36
profileImageView.layer.cornerRadius = profileImageView.frame.size.height/2;
profileImageView.clipsToBounds = YES;
profileImageView.layer.cornerRadius = profileImageView.frame.size.height/2;
profileImageView.clipsToBounds = YES;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文