gpt4 book ai didi

ios - 缩放 UIImage 以与 CGContextDrawImage 一起使用

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:00:35 25 4
gpt4 key购买 nike

我有一张尺寸为 480px x 480px 的图像,我想使用 CGContextDrawImage 将其显示在尺寸为 375px x 375px 的 View 中,如下所示。目前图像无法缩放以适合 View - 它是以全尺寸绘制的。请问如何调整下面的代码以缩放图像以适合 View ?

self.image = [UIImage imageNamed:@"image2.png"];
CGContextRef layerContext = CGLayerGetContext(drawingLayer);
CGContextSaveGState(layerContext);
UIGraphicsBeginImageContext (self.viewRect.size);
CGContextTranslateCTM(layerContext, 0, self.image.size.width);
CGContextScaleCTM(layerContext, 1.0, -1.0);
CGContextDrawImage(layerContext, self.viewRect, self.image.CGImage);
UIGraphicsEndImageContext();
CGContextRestoreGState(layerContext);

最佳答案

现在您可能会使用 UIGraphicsImageRenderer ,这让您摆脱了所有这些 CoreGraphics 调用的困扰:

CGRect rect = CGRectMake(0, 0, 375, 375);
UIImage *smallImage = [[[UIGraphicsImageRenderer alloc] initWithBounds:rect] imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
[self.image drawInRect:rect];
}];

但我原来的答案在下面。


CGContextDrawImage 函数将缩放图像以适应 View 。正如此功能的文档所述:

Draws an image into a graphics context.

Quartz scales the image—disproportionately, if necessary—to fit the bounds specified by the rect parameter.

唯一看起来非常可疑的是那一行:

CGContextTranslateCTM(layerContext, 0, self.image.size.width);

首先,您想按高度而不是宽度垂直平移。其次,您想按 viewRect 的高度进行平移,而不是 image 的高度。因此:

CGContextTranslateCTM(layerContext, 0, self.viewRect.size.height);

如果图像仍未正确缩放,我建议您仔细检查 viewRect。但是 CGContextDrawImage 肯定会绘制在指定的 CGRect 范围内缩放的图像。

关于ios - 缩放 UIImage 以与 CGContextDrawImage 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31194044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com