簡體   English   中英

使用CGAffineTransform從UIImageView保存UIImage

[英]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中將txty設置為零。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM