是否可以使用Aspect Fit调整大小在Core Graphics中显示图像?

时间:2012-01-14 22:19:34

标签: ios cocoa-touch uikit core-graphics

CALayer可以做到,而UIImageView可以做到这一点。我可以直接显示与Core Graphics相关的图像吗? UIImage drawInRect不允许我设置调整大小机制。

4 个答案:

答案 0 :(得分:11)

如果您已经链接 AVFoundation ,则在该框架中提供了一个方面适合函数:

CGRect AVMakeRectWithAspectRatioInsideRect(CGSize aspectRatio, CGRect boundingRect);

例如,要缩放图像以适合:

UIImage *image = …;
CRect targetBounds = self.layer.bounds;
// fit the image, preserving its aspect ratio, into our target bounds
CGRect imageRect = AVMakeRectWithAspectRatioInsideRect(image.size, 
                                                       targetBounds);

// draw the image
CGContextDrawImage(context, imageRect, image.CGImage);

答案 1 :(得分:5)

你需要自己做数学。例如:

// desired maximum width/height of your image
UIImage *image = self.imageToDraw;
CGRect imageRect = CGRectMake(10, 10, 42, 42); // desired x/y coords, with maximum width/height

// calculate resize ratio, and apply to rect
CGFloat ratio = MIN(imageRect.size.width / image.size.width, imageRect.size.height / image.size.height);
imageRect.size.width = imageRect.size.width * ratio;
imageRect.size.height = imageRect.size.height * ratio;

// draw the image
CGContextDrawImage(context, imageRect, image.CGImage);

或者,您可以嵌入UIImageView作为视图的子视图,为您提供易于使用的选项。为了获得类似的易用性和更好的性能,您可以在视图的图层中嵌入包含图像的图层。如果你选择沿着这条路走下去,这些方法中的任何一种都值得一个单独的问题。

答案 2 :(得分:1)

当然可以。它会以你通过的任何方式绘制图像。所以只需通过一个适合方面的矩形。当然,你必须自己做一点数学,但这很容易。

答案 3 :(得分:1)

这是解决方案

CGSize imageSize = yourImage.size;
CGSize viewSize = CGSizeMake(450, 340); // size in which you want to draw

float hfactor = imageSize.width / viewSize.width;
float vfactor = imageSize.height / viewSize.height;

float factor = fmax(hfactor, vfactor);

// Divide the size by the greater of the vertical or horizontal shrinkage factor
float newWidth = imageSize.width / factor;
float newHeight = imageSize.height / factor;

CGRect newRect = CGRectMake(xOffset,yOffset, newWidth, newHeight);
[image drawInRect:newRect];

- 礼貌https://stackoverflow.com/a/1703210