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

Ana*_*Ana 1 cocoa-touch core-graphics uikit ios

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

Phi*_*vin 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);
Run Code Online (Sandbox Code Playgroud)


Abh*_*ert 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);
Run Code Online (Sandbox Code Playgroud)

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