iOS - 在Button Round中创建UIImage

时间:2014-05-08 22:09:22

标签: ios objective-c uiimage

如今,每个人都喜欢它们的圆形图像。所以我想我也是。随着那说......

我将UIImage设置为UIButton的背景图像。我需要做的是使轮廓图完全圆润。这是我的代码......任何人都可以指出我正确的方向吗?

NSString* photoUrl = [NSString stringWithFormat:@"%@%@", URL_IMAGE_BASE, photoFileName];
NSURL *myurl2 = [NSURL URLWithString: photoUrl];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:myurl2]];
[_goToProfileEditButton setImage:image forState:UIControlStateNormal];
[_goToProfileEditButton setBackgroundImage:image forState:UIControlStateNormal];

3 个答案:

答案 0 :(得分:1)

使按钮成为完美的正方形(相同的宽度/高度),并使用按钮图层的cornerRadius属性,并将其设置为宽度/高度的一半。您需要导入QuartzCore标头才能访问layer属性。

答案 1 :(得分:0)

您可以做的是子类UIView并覆盖drawRect:方法,如下所示:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    CGContextAddEllipseInRect(context, rect);
    CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
    CGContextFillPath(context);
}

将视图的clipsToBounds属性设置为YES,并将图片视图添加为子类UIView的子视图。否则,您可以通过CGImageMaskCreate查看图像的屏蔽。

答案 2 :(得分:0)

如果您乐意掩盖按钮本身,那么玻利维亚的答案是最好的。

如果要从正方形创建圆形图像,则可以使用剪贴蒙版进行创建。它应该如下所示:

// start with the square image, from a file, the network, or wherever...
UIImage * squareImage = [UIImage imageNamed:@"squareImage.png"];
CGRect imageRect = CGRectMake(0, 0, squareImage.size.width, squareImage.size.height);
UIGraphicsBeginImageContextWithOptions(imageRect.size,NO,0.0);
UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:imageRect cornerRadius:imageRect.size.width/2.0f];
[path addClip];
[squareImage drawInRect:imageRect];
UIImage *circleImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// now circleImage contains the circle in the center of squareImage
相关问题