2011-11-14 58 views
3

我知道有可能在像UIImageView這樣的對象上有圓角(我之前做過)。但在這種情況下,我需要讓我的方形UIImage具有圓角。我知道這比僅僅對一個對象做這件事更困難,但我需要爲UIImage專門設計。爲UIImage添加圓角?

任何人都可以共享一個不是靜態的方法,並且可以在我已經創建的類中實現嗎?

我必須這樣做到UIImage,除非有可能向CCSprite添加圓角邊緣。

謝謝!

EDIT2:

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; 
} 
+0

這上面貼一個:http://blog.sallarp.com/iphone-uiimage-round-corners/如果你不這樣做像它靜態移除靜態和+。類似的問題:[UIImage圓角](http://stackoverflow.com/questions/262156/uiimage-rounded-corners) – Jano

+0

所以你說我的Edit1中的代碼將完成這項工作? –

+0

也之前與對象我將它設置爲可以說10的邊框半徑,我將如何使用此代碼與邊框寬度和邊框高度的參數?謝謝! –

回答

6

使用https://stackoverflow.com/a/8125604/412916與UIBezierPath夾代替。這很簡單。

使用代碼從 http://blog.sallarp.com/iphone-uiimage-round-corners/

// rounded corner 10x10 
UIImage *original = [UIImage imageNamed:@"original.png"]; 
UIImage *rounded = [self makeRoundCornerImage:original :10 :10]; 

+0

好吧,這樣才能清楚。如果我正在使用類中的代碼,那麼我只是使用我在edit2中發佈的代碼正確嗎? –

+0

是的,這是正確的。 – Jano

+0

謝謝並接受答案! –