ios - 正确裁剪和缩放 UIImage

标签 ios resize uiimage core-graphics crop

我正在尝试将图像裁剪成正方形,然后将其缩放到 200x200 的大小。这是我使用的代码,但它并不真正适合我。我得到的图像有时方向不同,或者未从中心裁剪,或者比应有的宽度更宽。

float scale = _avatar.image.scale;
UIImageOrientation orientation = _avatar.image.imageOrientation;

if(_avatar.image.size.width < _avatar.image.size.height){ // avatar is a UIImageView
    float startingY = (_avatar.image.size.height-_avatar.image.size.width)/2; // image is taller, determine the origin of the width-sized square, which will be the new image
    CGImageRef imageRef = CGImageCreateWithImageInRect([_avatar.image CGImage], CGRectMake(0, startingY, _avatar.image.size.width, _avatar.image.size.width));
    _avatar.image = [UIImage imageWithCGImage:imageRef scale:scale orientation:orientation];
    CGImageRelease(imageRef);
} else {
    float startingX = (_avatar.image.size.width-_avatar.image.size.height)/2; // image is wider, determine the origin of the height-sized square, which will be the new image
    CGImageRef imageRef = CGImageCreateWithImageInRect([_avatar.image CGImage], CGRectMake(startingX, 0, _avatar.image.size.height, _avatar.image.size.height));
    _avatar.image = [UIImage imageWithCGImage:imageRef scale:scale orientation:orientation];
    CGImageRelease(imageRef);
}

UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), YES, 0.0);
[_avatar.image drawInRect:CGRectMake(0, 0, 200, 200)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

必须怎样做才能得到正确的结果?

最佳答案

我建议您将此类别用于发布在 github 上的 UIImage .它们也是非常简单的类,您还可以使用它们来了解幕后的内容。

关于ios - 正确裁剪和缩放 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17994310/

相关文章:

iOS - 使 UIImage 与 UIButton 具有相同的大小

ios - 如何实现所需的横向和纵向布局(快速)

ios - 来自偏移量的时区名称/缩写

c - 使用可能重复的键调整单独链接的哈希表的大小

c++ - 更改数组大小 C++

ios - CIContext 错误访问崩溃

iOS 使 UIImage 的一部分透明

ios - 为什么 MPMoviePlayerController 全屏按钮图标在 iOS 10 中变为字幕图标?

java - 如何为TableView设置水平滚动条?

ios - 如何使用宽度缩放 UIImage 并保持比例