我使用了来自如何在iPhone上创建圆角UILabel?的答案以及如何在iPhone上制作具有透明度的圆角矩形视图?中的代码,生成了这段代码。
然后我意识到我回答了错误的问题(给出了一个圆角UILabel而不是UIImage),所以我使用了此代码进行更改:
使用View模板创建一个iPhone项目,在视图控制器中添加以下内容:
- (void)viewDidLoad
{
CGRect rect = CGRectMake(10, 10, 200, 100);
MyView *myView = [[MyView alloc] initWithFrame:rect];
[self.view addSubview:myView];
[super viewDidLoad];
}
MyView
只是UIImageView
的子类:
@interface MyView : UIImageView
{
}
我以前从未使用过图形上下文,但我设法拼凑出了这段代码。它缺少两个角的代码。如果您阅读代码,可以看到我如何实现此功能(通过删除一些CGContextAddArc
调用和代码中的一些半径值。所有角的代码都已经在那里,所以以此为起点并删除不需要创建的角部分。请注意,您也可以制作具有2或3个圆角的矩形。
这段代码还不完美,但我相信您能稍微整理一下。
static void addRoundedRectToPath(CGContextRef context, CGRect rect, float radius, int roundedCornerPosition)
{
if (roundedCornerPosition == 1) {
CGContextMoveToPoint(context, rect.origin.x, rect.origin.y + radius);
CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y + rect.size.height - radius);
CGContextAddArc(context, rect.origin.x + radius, rect.origin.y + rect.size.height - radius,
radius, M_PI / 4, M_PI / 2, 1);
CGContextAddLineToPoint(context, rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height);
CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y);
CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y);
}
if (roundedCornerPosition == 2) {
CGContextMoveToPoint(context, rect.origin.x, rect.origin.y);
CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y + rect.size.height);
CGContextAddLineToPoint(context, rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height);
CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y);
CGContextAddLineToPoint(context, rect.origin.x + radius, rect.origin.y);
CGContextAddArc(context, rect.origin.x + radius, rect.origin.y + radius, radius,
-M_PI / 2, M_PI, 1);
}
CGContextClosePath(context);
CGContextRestoreGState(context);
}
-(UIImage *)setImage
{
UIImage *img = [UIImage imageNamed:@"my_image.png"];
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, w, h);
addRoundedRectToPath(context, rect, 50, 1);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, rect, img.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
[img release];
return [UIImage imageWithCGImage:imageMasked];
}
alt text http://nevan.net/skitch/skitched-20100224-092237.png
别忘了你需要将 QuartzCore 框架添加进来才能让它工作。
UIView
会根据其autoresizingMask
自动调整子视图的大小,但是不支持该UIView
的子层不会自动调整大小,因此您需要手动调整。不过这很容易 - 每当您调整视图的大小(或在layoutSubviews
中如果您的视图是子类化的,甚至在您的视图控制器的viewWill/DidLayoutSubviews
方法中如果适用),获取对蒙版的引用 (CAShapeLayer *mask = (CAShapeLayer *)view.layer.mask;
),使用视图的新边界创建一个新的UIBezierPath
并更改路径 (mask.path = newPath.CGPath;
mask.frame = view.bounds;
)。 - Stuart