代码之家  ›  专栏  ›  技术社区  ›  joneswah

使用cgafinetransform保存uiimageview中的uiimage

  •  1
  • joneswah  · 技术社区  · 16 年前

    我在uiscrollview中有一个uiimageview,它允许用户对其执行任意数量的翻转和旋转操作。我有这一切工作,允许用户缩放,平移,翻转和旋转。现在我想能够把最后的图片保存成PNG格式。

    不管我怎么想…

    我看过很多类似的帖子,但大多数都只需要应用一个转换,比如旋转 Creating a UIImage from a rotated UIImageView

    我想应用用户“创建”的任何转换,这将是一系列的翻转和旋转连接在一起

    由于用户正在应用各种旋转、翻转等操作,因此我使用cgafinetransformconcat存储连接的转换。例如,当它们旋转时,我会:

    CGAffineTransform newTransform = CGAffineTransformMakeRotation(angle);
    self.theFullTransform = CGAffineTransformConcat(self.theFullTransform, newTransform);
    self.fullPhotoImageView.transform = self.theFullTransform;
    

    下面的方法是目前为止我所得到的最好的用全变换创建uiimage的方法,但是图像总是被翻译到错误的地方。图像是“偏移”的。我的猜测可能与使用cgafinetransformtranslate或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;
    }
    
    1 回复  |  直到 9 年前
        1
  •  1
  •   drawnonward    16 年前

    偏移量是可预测的,就像总是图像的一半,还是取决于atransform?

    struct CGAffineTransform {
      CGFloat a, b, c, d;
      CGFloat tx, ty;
    };
    

    如果是后者,设置 tx ty 使用前在atransform中归零。