gpt4 book ai didi

ios - 按比例调整 UIImage 的大小然后裁剪

转载 作者:可可西里 更新时间:2023-11-01 06:18:27 27 4
gpt4 key购买 nike

我正在使用此代码调整用相机拍摄的图像的大小。我按比例将其缩小为缩略图,但随后我想将其裁剪为 60x60 方形格式。我尝试合并:

CGImageRef imageRef = CGImageCreateWithImageInRect(CGImage, rect); 

但我没能让它正常工作。我如何使用 Core Graphics 做到这一点?

- (UIImage *) resizeCapturedImage:(UIImage *) img toWidth:(float) w{

CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(NULL,w,w, 8, 0, colorspace,kCGImageAlphaPremultipliedFirst);

CGContextDrawImage(ctx, CGRectMake(0, 0, w,img.size.width*w/img.size.height), img.CGImage);
CGImageRef thumb = CGBitmapContextCreateImage(ctx);
UIImage *final = [UIImage imageWithCGImage:thumb scale:1.0 orientation:UIImageOrientationRight];

return final;
}

最佳答案

我在这里放置了裁剪和调整图像大小的逻辑,根据您的要求使用它。

获取裁剪图像:

UIImage *croppedImg = nil;
CGRect cropRect = CGRectMake(AS YOu Need); // set frame as you need
croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect];

以下返回 UIImage 的方法(您想要的图像大小)

- (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect
{
//CGRect CropRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height+15);

CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

return cropped;
}

这里得到的是通过上述方法返回的Croped Image;

或调整大小

并且还使用以下方法对图像的特定高度宽度进行调整:

+ (UIImage*)resizeImage:(UIImage*)image withWidth:(CGFloat)width withHeight:(CGFloat)height
{
CGSize newSize = CGSizeMake(width, height);
CGFloat widthRatio = newSize.width/image.size.width;
CGFloat heightRatio = newSize.height/image.size.height;

if(widthRatio > heightRatio)
{
newSize=CGSizeMake(image.size.width*heightRatio,image.size.height*heightRatio);
}
else
{
newSize=CGSizeMake(image.size.width*widthRatio,image.size.height*widthRatio);
}


UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return newImage;
}

此方法返回 NewImage,具有您想要的特定大小。

关于ios - 按比例调整 UIImage 的大小然后裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19360701/

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