简体   繁体   English

iOS-使UIImage在按钮内变圆

[英]iOS - Make UIImage inside Button Round

Everybody loves them some round profile images these days. 如今,每个人都喜欢他们一些圆形的头像。 So I guess I do too. 所以我想我也是。 With that said... 照这样说...

I have a UIImage set as the background image of a UIButton. 我将UIImage设置为UIButton的背景图像。 What I need to do is make the profile picture completely rounded. 我需要做的是使个人资料图片完全四舍五入。 Here's my code ... can anyone point me in the right direction? 这是我的代码...谁能指出我正确的方向?

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];

Make the button a perfect square (same width/height) and use the cornerRadius property of the button layer and set it to be exactly half its width/height. 使按钮成为一个完美的正方形(宽度/高度相同),并使用按钮层的cornerRadius属性并将其设置为宽度/高度的一半。 You need to import the QuartzCore header to be able to access the layer property. 您需要导入QuartzCore标头才能访问layer属性。

What you could do is subclass UIView and override the drawRect: method like so: 您可以做的是子类UIView并重写drawRect:方法,如下所示:

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

Set the view's clipsToBounds property to YES and add your image view as a subview of your subclassed UIView . 将视图的clipsToBounds属性设置为YES然后将图像视图添加为子类UIView的子视图。 Otherwise you could look into masking with an image via CGImageMaskCreate . 否则,您可以通过CGImageMaskCreate使用图像进行CGImageMaskCreate

bolivia's answer is the best if you are happy to mask the button itself. 如果您愿意掩盖按钮本身,则玻利维亚的答案是最好的。

If you want to create a circle image from a square, then you can do that with a clipping mask. 如果要从正方形创建圆形图像,则可以使用剪贴蒙版进行。 It should be something like as follows: 它应如下所示:

// 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM