我使用以下代码制作椭圆形图像。
UIImage * fooImage = image;
CGRect imageRect = CGRectMake(0, 0, 291, 130);
UIGraphicsBeginImageContextWithOptions(imageRect.size,NO,0.0);
// create a bezier path defining rounded corners
UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(0.0, 0.0, CGRectGetWidth(img_blank.frame), CGRectGetHeight(img_blank.frame))];
// use this path for clipping in the implicit context
[path addClip];
// draw the image into the implicit context
[fooImage drawInRect:imageRect];
// save the clipped image from the implicit context into an image
UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext();
img_blank.image=maskedImage;
这里image_blank
是我正在使用的UIImage,如果宽度更大,高度更小的图像出现,那么它就不会拉伸。如果我更改了值,我就不会得到适合我UIImageview(img_blank)
的椭圆形状。
答案 0 :(得分:1)
此问题是您的矩形尺寸和图像尺寸不匹配。
当你: [fooImage drawInRect:imageRect];
图像将被绘制成偏向该矩形,您已将其定义为CGRectMake(0, 0, 291, 130);
要使其工作,您需要创建第二个矩形,扩展椭圆的矩形以匹配图像的宽高比。然后,您可以使用此第二个矩形绘制图像,以便图像在纵横填充椭圆。
这是我过去用于类似问题的一些伪代码:
// get the size of the image that we want to scale
CGSize imageSize = imageToDraw.size;
// get the size of the canvas we're trying to fill
CGSize canvasSize = imageRect.size;
// we need to see how the ratio of image width & height compare to the canvas
CGFloat horizontalRatio = canvasSize.width / imageSize.width;
CGFloat verticalRatio = canvasSize.height / imageSize.height;
// pick the ratio that requires the most scaling
CGFloat ratio = MAX(horizontalRatio, verticalRatio); //AspectFill
// calculate the size that we should draw the image so that it could fill
// the entire canvas with an aspect-fill rule
CGSize aspectFillSize = CGSizeMake(imageSize.width * ratio, imageSize.height * ratio);
// now draw the image, centering it and filling the canvas
[imageToDraw drawInRect:CGRectMake((canvasSize.width-aspectFillSize.width)/2,
(canvasSize.height-aspectFillSize.height)/2,
aspectFillSize.width,
aspectFillSize.height)];