And*_*dre 9 iphone xcode image crop uiscrollview
我在UIScrollView中有一个图像,可以滚动和缩放.
当用户按下按钮时,我希望代码从UIScrollView的任何部分创建一个图像,该图像位于我使用CGRect指定的区域内.
我已经看过用于裁剪UIImages的代码,但是我无法使其适应视图,因为它使用了CGContextDrawImage.
有什么想法吗?
干杯,安德烈
And*_*dre 28
我成功了.
这是我的解决方案,基于网络上的一些不同的解决方案:
- (UIImage *)imageByCropping:(UIScrollView *)imageToCrop toRect:(CGRect)rect
{
CGSize pageSize = rect.size;
UIGraphicsBeginImageContext(pageSize);
CGContextRef resizedContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(resizedContext, -imageToCrop.contentOffset.x, -imageToCrop.contentOffset.y);
[imageToCrop.layer renderInContext:resizedContext];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Run Code Online (Sandbox Code Playgroud)
您使用以下方式调用:
CGRect clippedRect = CGRectMake(0, 0, 320, 300);
picture.image = [self imageByCropping:myScrollView toRect:clippedRect];
Run Code Online (Sandbox Code Playgroud)