iOS如何将图像的一部分绘制到特定的矩形?

30byixjq  于 2023-07-01  发布在  iOS
关注(0)|答案(2)|浏览(104)

我想裁剪一张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;
}
cbjzeqam

cbjzeqam1#

让我们尝试使用以下代码块

- (UIImage*) getSubImageFromImage:(UIImage *)image
{
      // translated rectangle for drawing sub image
      CGRect drawRect = CGRectMake(10, 10, 50, 50);
      // Create Image Ref on Image
      CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
      // Get Cropped Image
      UIImage *img = [UIImage imageWithCGImage:imageRef];
      CGImageRelease(imageRef);
      return img;
}
798qvoo8

798qvoo82#

Swift方式:

指定要从图像中裁剪的帧时,可以使用CGImage.cropping(to:)
下面是一个 Package 为UIImage扩展的示例:

extension UIImage {
    func crop(frame: CGRect) -> UIImage {
        guard let croppedCGImage = cgImage?.cropping(to: frame) else {
            return self
        }
        return UIImage(cgImage: croppedCGImage)
    }
}

用途:

UIImage().crop(frame: CGRect())

相关问题