2

我正在开发一个应用程序,其功能包括平移、缩放和旋转图像。起初我实现了应用于图片的 UIImageView 的所有手势识别,然后我注意到实际图像保持不变 - 我需要对其进行修改。

我发现了一个关于 SO 处理此类问题的问题 -从旋转的 UIImageView 创建 UIImage - 我实际上能够使用 Magic Bullet Dave 提供的代码。但是,由于我的应用程序应该不仅支持旋转而且还支持图像的缩放,因此我不得不对其进行修改。他基本上写了一个方法来返回一个适合旋转图像的 CGRect。问题是我无法缩放所述 CGRect 以正确包含缩放图像。当我在应用程序中旋转图像(在模拟器中运行)然后观察保存用于测试目的的 png 版本时,CGRect 剪辑图像的顶部和底部角 - 图像越接近旋转 90 度,越多它被剪裁了。

这是返回 CGRect 的方法:

- (CGRect) getBoundingRectAfterRotation: (CGRect) rectangle byAngle: (CGFloat) angleOfRotation {

    // Calculate the width and height of the bounding rectangle using basic trig
    CGFloat newWidth = rectangle.size.width * fabs(cosf(angleOfRotation)) + rectangle.size.height * fabs(sinf(angleOfRotation));
    CGFloat newHeight = rectangle.size.height * fabs(cosf(angleOfRotation)) + rectangle.size.width * fabs(sinf(angleOfRotation));

    // Calculate the position of the origin
    CGFloat newX = rectangle.origin.x + ((rectangle.size.width - newWidth) / 2);
    CGFloat newY = rectangle.origin.y + ((rectangle.size.height - newHeight) / 2);

    // Create the new rectangle
    CGRect rotatedRect = CGRectMake(newX, newY, newWidth, newHeight);
    return CGRectApplyAffineTransform(rotatedRect, CGAffineTransformScale(originalState, theScale, theScale));
}

如您所见,我尝试获取旋转图像的 CGRect 并对其进行缩放 - 无济于事。然后用于创建实际图像:

CGFloat angle = totalAngle;
UIImage *viewImage;

// Get image width, height of the bounding rectangle
CGRect boundingRect = [self getBoundingRectAfterRotation: self.photoView.bounds byAngle:angle];

// Create a graphics context the size of the bounding rectangle
UIGraphicsBeginImageContext(boundingRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();

// Rotate and translate the context
CGAffineTransform transform = CGAffineTransformIdentity;
transform = CGAffineTransformTranslate(transform, boundingRect.size.width/2, boundingRect.size.height/2);
transform = CGAffineTransformRotate(transform, angle);
transform = CGAffineTransformScale(transform, theScale, -theScale);

CGContextConcatCTM(context, transform);

代码尚未清理,因为这显然还没有完成 - 目前我通过使 CGRect 大于必要的大小来解决这个问题,尽管我当然想避免这种情况。

欢迎任何帮助。

4

0 回答 0