我想裁剪一张200200的图片,裁剪的部分是(x=10,y=10,w=50,h=50)。然后把这部分绘制成新的500500的图像,新的矩形是(x=30,y=30,w=50,h=50),怎么做?
我可以用下面的方法得到图像的部分
- (UIImage*) getSubImageWithRect: (CGRect) rect {
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
// translated rectangle for drawing sub image
CGRect drawRect = CGRectMake(-rect.origin.x, -rect.origin.y, self.size.width, self.size.height);
// clip to the bounds of the image context
// not strictly necessary as it will get clipped anyway?
CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height));
// draw image
[self drawInRect:drawRect];
// grab image
UIImage* subImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return subImage;
}
2条答案
按热度按时间cbjzeqam1#
让我们尝试使用以下代码块
798qvoo82#
Swift方式:
指定要从图像中裁剪的帧时,可以使用
CGImage.cropping(to:)
。下面是一个 Package 为
UIImage
扩展的示例:用途: