如何给 UIImage 添加圆角?

3

我知道在像UIImageView这样的对象上可以设置圆角(我以前做过)。但是在这种情况下,我需要将我的正方形UIImage设置为圆角。我知道这比仅对一个对象进行操作更加困难,但我需要特别应用于UIImage。

有人能分享一种不是静态的方法,并且可以在我已经创建的类中实现吗?

除非可以将圆角边缘添加到CCSprite,否则我必须对UIImage执行此操作。

谢谢!

编辑2:

    void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)
{
    float fw, fh;
    if (ovalWidth == 0 || ovalHeight == 0) {
        CGContextAddRect(context, rect);
        return;
    }
    CGContextSaveGState(context);
    CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGContextScaleCTM (context, ovalWidth, ovalHeight);
    fw = CGRectGetWidth (rect) / ovalWidth;
    fh = CGRectGetHeight (rect) / ovalHeight;
    CGContextMoveToPoint(context, fw, fh/2);
    CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
    CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
    CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
    CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
    CGContextClosePath(context);
    CGContextRestoreGState(context);
}

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

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

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

        CGContextBeginPath(context);
        CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
        addRoundedRectToPath(context, rect, cornerWidth, cornerHeight);
        CGContextClosePath(context);
        CGContextClip(context);

        CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);

        CGImageRef imageMasked = CGBitmapContextCreateImage(context);
        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);
        [img release];

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

        [pool release];
    }

    return newImage;
}

这里有一个例子:http://blog.sallarp.com/iphone-uiimage-round-corners/ 如果你不想它是静态的,可以移除static和+。类似问题:UIImage rounded corners - Jano
那么你的意思是说我 Edit1 中的代码可以完成这项工作? - SimplyKiwi
还有,在使用对象之前,我将其设置为圆角半径,比如说10,那么在具有边框宽度和边框高度参数的这段代码中,我该如何做呢?谢谢! - SimplyKiwi
1个回答

6

好的,为了明确起见。如果我正在使用此类中的代码,则只需使用我在编辑2中发布的代码即可,对吗? - SimplyKiwi
代码似乎没有正确处理比例尺。此外,您应该在答案正文中发布代码。 - Jonny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接