Iphone UIImage圆角
我尝试在UIImage上获得圆角,到目前为止,我读到的,最简单的方法是使用遮罩图像。为此,我使用了Elements iPhone示例中的代码和我找到的一些图像大小调整代码。我的问题是resizedImage总是为零,我没有发现错误Iphone UIImage圆角,iphone,cocoa-touch,Iphone,Cocoa Touch,我尝试在UIImage上获得圆角,到目前为止,我读到的,最简单的方法是使用遮罩图像。为此,我使用了Elements iPhone示例中的代码和我找到的一些图像大小调整代码。我的问题是resizedImage总是为零,我没有发现错误 - (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize { CGSize imageSize = [self size]; float width = imageSize.w
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize
{
CGSize imageSize = [self size];
float width = imageSize.width;
float height = imageSize.height;
// scaleFactor will be the fraction that we'll
// use to adjust the size. For example, if we shrink
// an image by half, scaleFactor will be 0.5. the
// scaledWidth and scaledHeight will be the original,
// multiplied by the scaleFactor.
//
// IMPORTANT: the "targetHeight" is the size of the space
// we're drawing into. The "scaledHeight" is the height that
// the image actually is drawn at, once we take into
// account the ideal of maintaining proportions
float scaleFactor = 0.0;
float scaledWidth = targetSize.width;
float scaledHeight = targetSize.height;
CGPoint thumbnailPoint = CGPointMake(0,0);
// since not all images are square, we want to scale
// proportionately. To do this, we find the longest
// edge and use that as a guide.
if ( CGSizeEqualToSize(imageSize, targetSize) == NO )
{
// use the longeset edge as a guide. if the
// image is wider than tall, we'll figure out
// the scale factor by dividing it by the
// intended width. Otherwise, we'll use the
// height.
float widthFactor = targetSize.width / width;
float heightFactor = targetSize.height / height;
if ( widthFactor < heightFactor )
scaleFactor = widthFactor;
else
scaleFactor = heightFactor;
// ex: 500 * 0.5 = 250 (newWidth)
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the thumbnail in the frame. if
// wider than tall, we need to adjust the
// vertical drawing point (y axis)
if ( widthFactor < heightFactor )
thumbnailPoint.y = (targetSize.height - scaledHeight) * 0.5;
else if ( widthFactor > heightFactor )
thumbnailPoint.x = (targetSize.width - scaledWidth) * 0.5;
}
CGContextRef mainViewContentContext;
CGColorSpaceRef colorSpace;
colorSpace = CGColorSpaceCreateDeviceRGB();
// create a bitmap graphics context the size of the image
mainViewContentContext = CGBitmapContextCreate (NULL, targetSize.width, targetSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
// free the rgb colorspace
CGColorSpaceRelease(colorSpace);
if (mainViewContentContext==NULL)
return NULL;
//CGContextSetFillColorWithColor(mainViewContentContext, [[UIColor whiteColor] CGColor]);
//CGContextFillRect(mainViewContentContext, CGRectMake(0, 0, targetSize.width, targetSize.height));
CGContextDrawImage(mainViewContentContext, CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledWidth, scaledHeight), self.CGImage);
// Create CGImageRef of the main view bitmap content, and then
// release that bitmap context
CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext);
CGContextRelease(mainViewContentContext);
CGImageRef maskImage = [[UIImage imageNamed:@"Mask.png"] CGImage];
CGImageRef resizedImage = CGImageCreateWithMask(mainViewContentBitmapContext, maskImage);
CGImageRelease(mainViewContentBitmapContext);
// convert the finished resized image to a UIImage
UIImage *theImage = [UIImage imageWithCGImage:resizedImage];
// image is retained by the property setting above, so we can
// release the original
CGImageRelease(resizedImage);
// return the image
return theImage;
}
-(UIImage*)图像按比例缩放到大小:(CGSize)targetSize
{
CGSize imageSize=[自身大小];
浮动宽度=imageSize.width;
浮动高度=imageSize.height;
//scaleFactor将是我们将
//用于调整大小。例如,如果我们缩小
//将图像减半,scaleFactor将为0.5
//scaledWidth和scaledHeight将为原始值,
//乘以scaleFactor。
//
//重要提示:“TargetLight”是空间的大小
//我们正在接近。缩放高度就是
//一旦我们考虑到
//考虑保持比例的理想
float scaleFactor=0.0;
浮动缩放宽度=targetSize.width;
浮动缩放高度=targetSize.height;
CGPoint thumbnailPoint=CGPointMake(0,0);
//因为不是所有的图像都是正方形的,所以我们需要缩放
//按比例。要做到这一点,我们找到最长的
//边缘,并以此作为指导。
if(CGSizeEqualToSize(imageSize,targetSize)==否)
{
//使用longeset边作为参考。如果
//图像比高宽,我们会弄清楚的
//比例因子除以
//预期宽度。否则,我们将使用
//高度。
浮动宽度系数=targetSize.width/宽度;
浮动高度系数=targetSize.height/高度;
if(宽度系数<高度系数)
scaleFactor=宽度因子;
其他的
比例因子=高度因子;
//ex:500*0.5=250(新宽度)
scaledWidth=宽度*缩放因子;
缩放高度=高度*缩放因子;
//将缩略图置于框架的中心。如果
//宽于高,我们需要调整
//垂直绘图点(y轴)
if(宽度系数<高度系数)
thumbnailPoint.y=(targetSize.height-缩放高度)*0.5;
否则如果(宽度因子>高度因子)
thumbnailPoint.x=(targetSize.width-scaledWidth)*0.5;
}
CGContextRef mainViewContentContext;
CGCOLORSPACTEREF色彩空间;
colorSpace=CGColorSpaceCreateDeviceRGB();
//根据图像大小创建位图图形上下文
mainViewContentContext=CGBitmapContextCreate(NULL,targetSize.width,targetSize.height,8,0,colorSpace,KCGimageAlphaPremultipledLast);
//释放rgb颜色空间
CGCOLORSPACTERELEASE(色彩空间);
if(mainViewContentContext==NULL)
返回NULL;
//CGContextSetFillColorWithColor(mainViewContentContext,[[UIColor whiteColor]CGColor]);
//CGContextFillRect(mainViewContentContext,CGRectMake(0,0,targetSize.width,targetSize.height));
CGContextDrawImage(mainViewContentContext,CGRectMake(thumbnailPoint.x,thumbnailPoint.y,scaledWidth,scaledHeight),self.CGImage);
//创建主视图位图内容的CGImageRef,然后
//释放位图上下文
CGImageRef mainViewContentBitmapContext=CGBitmapContextCreateImage(mainViewContentContext);
CGContextRelease(mainViewContentContext);
CGImageRef maskImage=[[UIImage IMAGENAME:@“Mask.png”]CGImage];
CGImageRef resizedImage=CGImageCreateWithMask(mainViewContentBitmapContext,maskImage);
CGImageRelease(mainViewContentBitmapContext);
//将已完成大小调整的图像转换为UIImage
UIImage*theImage=[UIImage imageWithCGImage:resizedImage];
//图像由上面的属性设置保留,因此我们可以
//发布原件
CGImageRelease(resizedImage);
//返回图像
返回图像;
}
依我看,除非你绝对需要在代码中这样做,只要在上面覆盖一个图像就行了
类似于
- (void)drawRect:(CGRect)rect
{
// Drawing code
[backgroundImage drawInRect:rect];
[buttonOverlay drawInRect:rect];
}
实际上,除了在那里缩放之外,你什么都没做。您需要做的是通过使用CGPath剪裁图像来“遮罩”图像的角点。例如—
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginTransparencyLayerWithRect(context, self.frame, NULL);
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
CGFloat roundRadius = (radius) ? radius : 12.0;
CGFloat minx = CGRectGetMinX(self.frame), midx = CGRectGetMidX(self.frame), maxx = CGRectGetMaxX(self.frame);
CGFloat miny = CGRectGetMinY(self.frame), midy = CGRectGetMidY(self.frame), maxy = CGRectGetMaxY(self.frame);
// draw the arcs, handle paths
CGContextMoveToPoint(context, minx, midy);
CGContextAddArcToPoint(context, minx, miny, midx, miny, roundRadius);
CGContextAddArcToPoint(context, maxx, miny, maxx, midy, roundRadius);
CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, roundRadius);
CGContextAddArcToPoint(context, minx, maxy, minx, midy, roundRadius);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFill);
CGContextEndTransparencyLayer(context);
}
我建议查看Quartz 2D编程指南或其他一些示例。问题在于使用了返回全黑图像的CGImageCreateWithMask。我找到的解决方案是使用CGContextClipToMask:
CGContextRef mainViewContentContext;
CGColorSpaceRef colorSpace;
colorSpace = CGColorSpaceCreateDeviceRGB();
// create a bitmap graphics context the size of the image
mainViewContentContext = CGBitmapContextCreate (NULL, targetSize.width, targetSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
// free the rgb colorspace
CGColorSpaceRelease(colorSpace);
if (mainViewContentContext==NULL)
return NULL;
CGImageRef maskImage = [[UIImage imageNamed:@"mask.png"] CGImage];
CGContextClipToMask(mainViewContentContext, CGRectMake(0, 0, targetSize.width, targetSize.height), maskImage);
CGContextDrawImage(mainViewContentContext, CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledWidth, scaledHeight), self.CGImage);
// Create CGImageRef of the main view bitmap content, and then
// release that bitmap context
CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext);
CGContextRelease(mainViewContentContext);
// convert the finished resized image to a UIImage
UIImage *theImage = [UIImage imageWithCGImage:mainViewContentBitmapContext];
// image is retained by the property setting above, so we can
// release the original
CGImageRelease(mainViewContentBitmapContext);
// return the image
return theImage;
它使用剪辑而不是遮罩的原因似乎是颜色空间 苹果的文档如下 面具
面具。如果遮罩是图像,则它必须位于DeviceGray颜色空间中,不得具有alpha分量,并且自身不得被图像遮罩或遮罩颜色遮罩。如果遮罩与image参数指定的图像大小不同,则Quartz会缩放遮罩以适合图像。如果使用UIImageView显示图像,则只需执行以下操作:
imageView.layer.cornerRadius = 5.0;
imageView.layer.masksToBounds = YES;
并添加边框:
imageView.layer.borderColor = [UIColor lightGrayColor].CGColor;
imageView.layer.borderWidth = 1.0;
我相信您必须导入
并与之链接,才能使上述代码正常工作。这些行如何
// Get your image somehow
UIImage *image = [UIImage imageNamed:@"image.jpg"];
// Begin a new image that will be the new image with the rounded corners
// (here with the size of an UIImageView)
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
// Add a clip before drawing anything, in the shape of an rounded rect
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds
cornerRadius:10.0] addClip];
// Draw your image
[image drawInRect:imageView.bounds];
// Get the image, here setting the UIImageView image
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
// Lets forget about that we were drawing
UIGraphicsEndImageContext();
大家好,试试这个代码
+ (UIImage *)roundedRectImageFromImage:(UIImage *)image withRadious:(CGFloat)radious {
if(radious == 0.0f)
return image;
if( image != nil) {
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = image.size.height;
CGRect rect = CGRectMake(0.0f, 0.0f, imageWidth, imageHeight);
UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
const CGFloat scale = window.screen.scale;
UIGraphicsBeginImageContextWithOptions(rect.size, NO, scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSaveGState(context);
CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM (context, radious, radious);
CGFloat rectWidth = CGRectGetWidth (rect)/radious;
CGFloat rectHeight = CGRectGetHeight (rect)/radious;
CGContextMoveToPoint(context, rectWidth, rectHeight/2.0f);
CGContextAddArcToPoint(context, rectWidth, rectHeight, rectWidth/2.0f, rectHeight, radious);
CGContextAddArcToPoint(context, 0.0f, rectHeight, 0.0f, rectHeight/2.0f, radious);
CGContextAddArcToPoint(context, 0.0f, 0.0f, rectWidth/2.0f, 0.0f, radious);
CGContextAddArcToPoint(context, rectWidth, 0.0f, rectWidth, rectHeight/2.0f, radious);
CGContextRestoreGState(context);
CGContextClosePath(context);
CGContextClip(context);
[image drawInRect:CGRectMake(0.0f, 0.0f, imageWidth, imageHeight)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
return nil;
}
干杯 我根据@epatel的精彩回答,在swift中创建了一个
UIImage
-扩展:
extension UIImage{
var roundedImage: UIImage {
let rect = CGRect(origin:CGPoint(x: 0, y: 0), size: self.size)
UIGraphicsBeginImageContextWithOptions(self.size, false, 1)
UIBezierPath(
roundedRect: rect,
cornerRadius: self.size.height
).addClip()
self.drawInRect(rect)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
在故事板中测试:
要创建圆角图像,我们可以使用quartzcore 首先,如何添加QuartzCore框架
Click project -Targets
->project
->BuildPhase
->Link Binary with Libraries
->Then click + symbol finally select from list and add it
否则
Click project -Targets
->Targets
->general
->Linked Frameworks and Libraries
->Then click + symbol finally select from list and add the QuartzCore framework
现在输入
#import <QuartzCore/QuartzCore.h>
使用图像维度时,创建圆形图像非常容易
cell.messageImage.layer.cornerRadius = image.size.width / 2
cell.messageImage.layer.masksToBounds = true
找出最佳且简单的方法如下(没有答案):
非常简单,而且做得很好。我正在努力绕过故事板中UIImage框的各个角落。我的UIImage有一个名为image的IBOutlet。在阅读了一堆关于这里的帖子后,我简单地添加了3行,效果非常好
import UIKit
然后在viewDidLoad中:
image.layer.cornerRadius = 20.0
image.layer.masksToBounds = true
这适用于Xcode 9中的iOS 11.1。扩展,具有正确的比例,
UIImageView *imageView;
imageView.layer.cornerRadius = imageView.frame.size.width/2.0f;
imageView.layer.masksToBounds = TRUE;
import UIKit
image.layer.cornerRadius = 20.0
image.layer.masksToBounds = true
extension UIImage {
public func rounded(radius: CGFloat) -> UIImage {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()
draw(in: rect)
return UIGraphicsGetImageFromCurrentImageContext()!
}
}
let imageView = UIImageView(image: UIImage(named: "myImage"))
imageView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
imageView.layer.cornerRadius = 10.0