[英]Save a UIImage from a UIImageView with CGAffineTransform
我在UIScrollView中有一个UIImageView,它使用户能够对其执行任意数量的翻转和旋转操作。 我完成了所有这一切,使用户可以缩放,平移,翻转和旋转。 现在,我希望能够将最终图像保存为png。
但是它正在努力解决这个问题...
我看过很多其他与此类似的帖子,但大多数只需要应用单个变换(例如旋转),例如从旋转的UIImageView创建UIImage。
我想应用用户“创建”的任何变换,它将一系列翻转和旋转串联在一起
当用户应用各种旋转,翻转等操作时,我使用CGAffineTransformConcat存储了级联变换。 例如,当他们旋转时,我这样做:
CGAffineTransform newTransform = CGAffineTransformMakeRotation(angle);
self.theFullTransform = CGAffineTransformConcat(self.theFullTransform, newTransform);
self.fullPhotoImageView.transform = self.theFullTransform;
到目前为止,以下方法是我创建具有完整转换的UIImage的最佳方法,但是图像始终在错误的位置转换。 例如,图像“偏移”。 我的猜测与使用CGAffineTransformTranslate或CGContextDrawImage中设置的错误边界有关。
有人有什么想法吗? 我以为应该这样似乎很难...
- (UIImage *) translateImageFromImageView: (UIImageView *) imageView withTransform:(CGAffineTransform) aTransform
{
UIImage *rotatedImage;
// Get image width, height of the bounding rectangle
CGRect boundingRect = CGRectApplyAffineTransform(imageView.bounds, aTransform);
// Create a graphics context the size of the bounding rectangle
UIGraphicsBeginImageContext(boundingRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform transform = CGAffineTransformIdentity;
//I think this translaton is the problem?
transform = CGAffineTransformTranslate(transform, boundingRect.size.width/2, boundingRect.size.height/2);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
transform = CGAffineTransformConcat(transform, aTransform);
CGContextConcatCTM(context, transform);
// Draw the image into the context
// or the boundingRect is incorrect here?
CGContextDrawImage(context, boundingRect, imageView.image.CGImage);
// Get an image from the context
rotatedImage = [UIImage imageWithCGImage: CGBitmapContextCreateImage(context)];
// Clean up
UIGraphicsEndImageContext();
return rotatedImage;
}
偏移量是可预测的吗?像总是图像的一半一样,还是依赖于Transform?
struct CGAffineTransform {
CGFloat a, b, c, d;
CGFloat tx, ty;
};
如果是后者,请在使用前在aTransform中将tx
和ty
设置为零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.