在iOS中通过转换绘制UIImage



我有一些可转换的UIImageViews(装饰在照片上),用户可以拖动、捏和旋转。编辑后,我希望应用程序生成最终图像。如何在考虑了UIImageViews的transform属性的情况下绘制它们。

我的第一个解决方案是使用renderInContext,但它只能生成320x480的图像。我可以生成任何分辨率的图像吗?

然后我使用如下代码:

UIGraphicsBeginImageContext(CGSizeMake(640.0f, 896.0f));
CGContextRef currentContext = UIGraphicsGetCurrentContext();
UIImage *backgroundImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"fittingBackground" ofType:@"jpg"]];
[backgroundImage drawInRect:CGRectMake(0.0f, 0.0f, 640.0f, 896.0f)];
CGContextSaveGState(currentContext);
CGContextConcatCTM(currentContext, self.photoImageView.transform);
CGRect photoFrame = self.photoImageView.frame;
[self.photoImageView.image drawInRect:CGRectMake(photoFrame.origin.x * 2, photoFrame.origin.y * 2, photoFrame.size.width * 2, photoFrame.size.height * 2)];
CGContextRestoreGState(currentContext);
CGContextSaveGState(currentContext);
CGContextConcatCTM(currentContext, self.productImageView.transform);
CGRect productFrame = self.productImageView.frame;
[self.productImageView.image drawInRect:CGRectMake(productFrame.origin.x * 2, productFrame.origin.y * 2, productFrame.size.width * 2, productFrame.size.height * 2)];
CGContextRestoreGState(currentContext);
UIImage *resultImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(currentContext)];
UIGraphicsEndImageContext();

然而,结果似乎很奇怪。我已经记录了帧、边界和中心。我不知道在应用转换后,我应该在drawInRect中使用哪个Rect

试试这个,

-(void)drawBackgroundInLayer:(CALayer*)destinationLayer {
    CGFloat scaledFactor = [[UIScreen mainScreen] scale];
    CGRect layerFrame = destinationLayer.frame;
    CGRect scaledRect = CGRectMake(layerFrame.origin.x, 
                                   layerFrame.origin.y, 
                                   (layerFrame.size.width)*scaledFactor, 
                                   (layerFrame.size.height)*scaledFactor);
    // Get the size and do some drawings
    CGSize sizeBack = CGSizeMake(layerFrame.size.width*scaledFactor, layerFrame.size.height*scaledFactor);
    UIGraphicsBeginImageContext(sizeBack);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 0., 0., 0., 1.);
    drawBorder(context, scaledRect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    if (destinationLayer) {
        [destinationLayer setContents:(id)img.CGImage];
    }
}

最重要的线路是UIGraphicsBeginImageContext(sizeBack);UIImage*img=UIGraphicsGetImageFromCurrentImageContext();

最新更新