ios iPhone 以编程方式裁剪方形图像以显示为圆形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9585819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iPhone programmatically crop a square image to appear as circle
提问by Alex Stone
I'm trying to create an image for a custom style UIButton using an image from the camera roll on iPhone. The button has a circular background and effectively appears as a circle. Now I need an image to go in the middle of the button that also appears round.
我正在尝试使用 iPhone 上相机胶卷中的图像为自定义样式 UIButton 创建图像。该按钮具有圆形背景并有效地显示为圆形。现在我需要一个图像进入也出现圆形的按钮中间。
How do I cut a square UIImage to appear round with transparency outside of the round area?
如何切割方形 UIImage 使其在圆形区域外具有透明性?
If masking is involved, do I need to pre-render a mask or can I create one programmatically(ex: a circle)?
如果涉及遮罩,我需要预先渲染遮罩还是可以通过编程方式创建遮罩(例如:圆形)?
Thank you!
谢谢!
回答by Novarg
I have never done anything like that, but try using QuartzCoreframework and its' cornerRadiusproperty. Example:
我从来没有做过这样的事情,但尝试使用QuartzCore框架及其cornerRadius属性。例子:
#import <QuartzCore/QuartzCore.h>
//some other code ...
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
imgView.layer.cornerRadius = 10.0f;
play around with it a bit and you will get what you want.
稍微玩一下,你就会得到你想要的。
Hope it helps
希望能帮助到你
回答by calimarkus
Yes you can use CoreGraphicsto draw the mask dynamically.
Then you can create the masked image.
是的,您可以使用CoreGraphics动态绘制蒙版。然后您可以创建蒙版图像。
Example for masking:
屏蔽示例:
- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage
{
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef maskedImageRef = CGImageCreateWithMask([image CGImage], mask);
UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];
CGImageRelease(maskedImageRef);
CGImageRelease(mask);
return maskedImage;
}
回答by Chris Nelson
I started looking into this a couple of weeks back. I tried all the suggestions here, none of which worked well. In the great tradition of RTFM I went and read Apple's documentation on Quartz 2D Programmingand came up with this. Please try it out and let me know how you go.
几周前我开始研究这个。我尝试了这里的所有建议,但没有一个效果很好。在 RTFM 的伟大传统中,我去阅读了 Apple 关于Quartz 2D Programming的文档并提出了这个。请尝试一下,让我知道您的进展情况。
The code could be fairly easily altered to crop to an elipse, or any other shape defined by a path.
可以很容易地修改代码以裁剪为椭圆形或由路径定义的任何其他形状。
Make sure you include Quartz 2D in your project.
确保在项目中包含 Quartz 2D。
#include <math.h>
+ (UIImage*)circularScaleNCrop:(UIImage*)image: (CGRect) rect{
// This function returns a newImage, based on image, that has been:
// - scaled to fit in (CGRect) rect
// - and cropped within a circle of radius: rectWidth/2
//Create the bitmap graphics context
UIGraphicsBeginImageContextWithOptions(CGSizeMake(rect.size.width, rect.size.height), NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
//Get the width and heights
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = image.size.height;
CGFloat rectWidth = rect.size.width;
CGFloat rectHeight = rect.size.height;
//Calculate the scale factor
CGFloat scaleFactorX = rectWidth/imageWidth;
CGFloat scaleFactorY = rectHeight/imageHeight;
//Calculate the centre of the circle
CGFloat imageCentreX = rectWidth/2;
CGFloat imageCentreY = rectHeight/2;
// Create and CLIP to a CIRCULAR Path
// (This could be replaced with any closed path if you want a different shaped clip)
CGFloat radius = rectWidth/2;
CGContextBeginPath (context);
CGContextAddArc (context, imageCentreX, imageCentreY, radius, 0, 2*M_PI, 0);
CGContextClosePath (context);
CGContextClip (context);
//Set the SCALE factor for the graphics context
//All future draw calls will be scaled by this factor
CGContextScaleCTM (context, scaleFactorX, scaleFactorY);
// Draw the IMAGE
CGRect myRect = CGRectMake(0, 0, imageWidth, imageHeight);
[image drawInRect:myRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Include the following code in your UIView class replacing "monk2.png" with your own image name.
在 UIView 类中包含以下代码,用您自己的图像名称替换“monk2.png”。
- (void)drawRect:(CGRect)rect
{
UIImage *originalImage = [UIImage imageNamed:[NSString stringWithFormat:@"monk2.png"]];
CGFloat oImageWidth = originalImage.size.width;
CGFloat oImageHeight = originalImage.size.height;
// Draw the original image at the origin
CGRect oRect = CGRectMake(0, 0, oImageWidth, oImageHeight);
[originalImage drawInRect:oRect];
// Set the newRect to half the size of the original image
CGRect newRect = CGRectMake(0, 0, oImageWidth/2, oImageHeight/2);
UIImage *newImage = [self circularScaleNCrop:originalImage :newRect];
CGFloat nImageWidth = newImage.size.width;
CGFloat nImageHeight = newImage.size.height;
//Draw the scaled and cropped image
CGRect thisRect = CGRectMake(oImageWidth+10, 0, nImageWidth, nImageHeight);
[newImage drawInRect:thisRect];
}
回答by ndnguru
Here is a quick way to create rounded corners on a square ImageView to make it look like a perfect circle. Basically you apply a corner radius equal to 1/2 the width (width == height on a square image).
这是在方形 ImageView 上创建圆角的快速方法,使其看起来像一个完美的圆形。基本上,您应用的角半径等于宽度的 1/2(正方形图像上的宽度 == 高度)。
#import <QuartzCore/QuartzCore.h> //you need QuartzCore
...
float width = imageView.bounds.size.width; // we can also use the frame property instead of bounds since we just care about the Size and don't care about position
imageView.layer.cornerRadius = width/2;
回答by AP_
{
imageView.layer.cornerRadius = imageView.frame.size.height /2;
imageView.layer.masksToBounds = YES;
imageView.layer.borderWidth = 0;
}
回答by Nikolay Dyankov
回答by Igor
I have another solution:
我有另一个解决方案:
- (UIImage *)roundedImageWithRect:(CGRect)rect radius:(CGFloat)radius
{
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, rect.size.width, rect.size.height) cornerRadius:radius];
CGFloat imageRatio = self.size.width / self.size.height;
CGSize imageSize = CGSizeMake(rect.size.height * imageRatio, rect.size.height);
CGRect imageRect = CGRectMake(0, 0, imageSize.width, imageSize.height);
[path addClip];
[self drawInRect:imageRect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
This variant is better for performance than set cornerRadius directly.
与直接设置cornerRadius 相比,此变体的性能更好。
回答by aaroncatlin
Personally, I'd create a transparent circle image with opaque corners to overlay the photo. This solution is only suitable where you will be placing the image in one place on the UI, and assumes the opaque corners will blend in with the background.
就个人而言,我会创建一个带有不透明角的透明圆形图像来覆盖照片。此解决方案仅适用于您将图像放置在 UI 上的一个位置的情况,并假设不透明的角落将与背景融为一体。
回答by Dilip Rajkumar
Following is the answer I given in How to crop UIImage on oval shape or circle shape?to make the image circle. It works for me..
以下是我在如何在椭圆形或圆形上裁剪 UIImage 中给出的答案?使图像圈。这个对我有用..
Download the Support archive file
#import "UIImage+RoundedCorner.h"
#import "UIImage+Resize.h"
Following lines used to resize the image and convert in to round with radius
以下几行用于调整图像大小并转换为具有半径的圆形
UIImage *mask = [UIImage imageNamed:@"mask.jpg"];
mask = [mask resizedImage:CGSizeMake(47, 47) interpolationQuality:kCGInterpolationHigh ];
mask = [mask roundedCornerImage:23.5 borderSize:1];
回答by n.by.n
Just use
只需使用
_profilePictureImgView.layer.cornerRadius = 32.0f;
_profilePictureImgView.layer.masksToBounds = YES;

