【发布时间】:2012-01-14 22:19:34
【问题描述】:
CALayer 可以做到,UIImageView 可以做到。我可以使用 Core Graphics 直接显示具有宽高比的图像吗? UIImage drawInRect 不允许我设置调整大小机制。
【问题讨论】:
标签: ios cocoa-touch uikit core-graphics
CALayer 可以做到,UIImageView 可以做到。我可以使用 Core Graphics 直接显示具有宽高比的图像吗? UIImage drawInRect 不允许我设置调整大小机制。
【问题讨论】:
标签: ios cocoa-touch uikit core-graphics
如果您已经在链接 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);
【讨论】:
您需要自己计算。例如:
// 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 作为视图的子视图,这为您提供了易于使用的选项。为了类似的易用性但更好的性能,您可以在视图层中嵌入包含图像的层。如果您选择走这条路,这两种方法中的任何一种都值得单独提出一个问题。
【讨论】:
当然可以。它会在您通过的任何矩形中绘制图像。所以只需传递一个适合方面的矩形。当然,您必须自己做一些数学运算,但这很容易。
【讨论】:
解决办法
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];
【讨论】: