UIImage的裁剪中心广场 [英] Cropping center square of UIImage

查看:150
本文介绍了UIImage的裁剪中心广场的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这就是我到目前为止所做的。我使用从相机捕获的UIImage,可以在景观中裁剪中心广场。由于某种原因,这不会像预期的那样转换为纵向模式。我将发布我的代码和日志仅供参考。

So here's where I've made it so far. I am using a UIImage captured from the camera and can crop the center square when in landscape. For some reason this doesn't translate to portrait mode as expected. I'll post my code and logs just for reference.

代码:

CGRect squareRect = CGRectMake(offsetX, offsetY, newWidth, newHeight);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], squareRect);
image = [UIImage imageWithCGImage:imageRef scale:1 orientation:image.imageOrientation];

人像结果(不是方形):

Portrait results (not square):

original image size: {1536, 2048}, with orientation: 3
squareRect: {{0, 256}, {1536, 1536}}
new image size: {1280, 1536}, with orientation: 3 <--- not expected

景观结果( square):

Landscape results (square):

original image size: {2048, 1536}, with orientation: 1
squareRect: {{256, 0}, {1536, 1536}}
new image size: {1536, 1536}, with orientation: 1

这是CGImageCreateWithImageInRect()中的错误还是我在这里遗漏了什么?

Is this a bug within CGImageCreateWithImageInRect() or am I missing something here?

推荐答案

我想这里将是完美的解决方案!
toSize 尺寸上裁剪图像基础并不是一个好主意。当图像分辨率(大小)非常大时,它看起来很奇怪。
以下代码将根据 toSize 比率裁剪图像。

@改进BlackRider 的回答。

I think here would be the perfect solution!
It is NOT good idea to crop image basis on the toSize's size. It will look weird when the image resolution (size) is very large.
Following code will crop the image as per the toSize's ratio.
Improved from @BlackRider's answer.

- (UIImage *)imageByCroppingImage:(UIImage *)image toSize:(CGSize)size
{
    double newCropWidth, newCropHeight;

    //=== To crop more efficently =====//
    if(image.size.width < image.size.height){
         if (image.size.width < size.width) {
                 newCropWidth = size.width;
          }
          else {
                 newCropWidth = image.size.width;
          }
          newCropHeight = (newCropWidth * size.height)/size.width;
    } else {
          if (image.size.height < size.height) {
                newCropHeight = size.height;
          }
          else {
                newCropHeight = image.size.height;
          }
          newCropWidth = (newCropHeight * size.width)/size.height;
    }
    //==============================//

    double x = image.size.width/2.0 - newCropWidth/2.0;
    double y = image.size.height/2.0 - newCropHeight/2.0;

    CGRect cropRect = CGRectMake(x, y, newCropWidth, newCropHeight);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    UIImage *cropped = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);

    return cropped;
}

这篇关于UIImage的裁剪中心广场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆