图像变得拉伸,同时制作椭圆形的uiimage

问题描述 投票:0回答:1

我正在使用以下代码来制作椭圆形图像。

 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)的椭圆形状。

ios objective-c uiimageview uiimage
1个回答
1
投票

此问题是您的rect大小和图像大小不匹配。

当你:[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)];
© www.soinside.com 2019 - 2024. All rights reserved.