gpt4 book ai didi

iphone - 调整大小并裁剪图像居中

转载 作者:IT王子 更新时间:2023-10-29 08:20:30 30 4
gpt4 key购买 nike

所以目前我正在尝试裁剪图片并调整其大小以使其适合特定尺寸而不丢失比例。

一张小图来说明我的意思:

alt text

我玩了一下 vocaro's categories但它们不适用于 png,并且在处理 gif 时有问题。图像也不会被裁剪。

有没有人建议如何以最佳方式调整大小,或者可能有指向现有库/类别/其他内容的链接?

感谢所有提示!

p.s.: ios 是否实现了“选择摘录”以便我有正确的比例并且只需要缩放它?!

最佳答案

此方法将执行您想要的操作,并且是 UIImage 的一个类别,以便于使用。我先调整大小然后裁剪,如果你想裁剪然后调整大小,你可以很容易地切换代码。函数中的边界检查纯粹是说明性的。您可能想要做一些不同的事情,例如将 crop rect 相对于 outputImage 尺寸居中,但这应该让您足够接近以进行您需要的任何其他更改。

@implementation UIImage( resizeAndCropExample )

- (UIImage *) resizeToSize:(CGSize) newSize thenCropWithRect:(CGRect) cropRect {
CGContextRef context;
CGImageRef imageRef;
CGSize inputSize;
UIImage *outputImage = nil;
CGFloat scaleFactor, width;

// resize, maintaining aspect ratio:

inputSize = self.size;
scaleFactor = newSize.height / inputSize.height;
width = roundf( inputSize.width * scaleFactor );

if ( width > newSize.width ) {
scaleFactor = newSize.width / inputSize.width;
newSize.height = roundf( inputSize.height * scaleFactor );
} else {
newSize.width = width;
}

UIGraphicsBeginImageContext( newSize );

context = UIGraphicsGetCurrentContext();

// added 2016.07.29, flip image vertically before drawing:
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, newSize.height);
CGContextScaleCTM(context, 1, -1);
CGContextDrawImage(context, CGRectMake(0, 0, newSize.width, newSize.height, self.CGImage);

// // alternate way to draw
// [self drawInRect: CGRectMake( 0, 0, newSize.width, newSize.height )];

CGContextRestoreGState(context);

outputImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

inputSize = newSize;

// constrain crop rect to legitimate bounds
if ( cropRect.origin.x >= inputSize.width || cropRect.origin.y >= inputSize.height ) return outputImage;
if ( cropRect.origin.x + cropRect.size.width >= inputSize.width ) cropRect.size.width = inputSize.width - cropRect.origin.x;
if ( cropRect.origin.y + cropRect.size.height >= inputSize.height ) cropRect.size.height = inputSize.height - cropRect.origin.y;

// crop
if ( ( imageRef = CGImageCreateWithImageInRect( outputImage.CGImage, cropRect ) ) ) {
outputImage = [[[UIImage alloc] initWithCGImage: imageRef] autorelease];
CGImageRelease( imageRef );
}

return outputImage;
}

@end

关于iphone - 调整大小并裁剪图像居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3955189/

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