如何从另一个图像的一部分创建图像?

时间:2016-01-20 19:40:16

标签: ios swift uiimage

如何在iOS swift中从其他图像创建图像?

E.g。如果我的图像(A)是1000像素×1000像素。如何从图像中间(A)创建200像素×200像素的图像(B)。

1 个答案:

答案 0 :(得分:0)

您可以在Core Graphics中轻松完成此操作......

func getSubImage(image:UIImage, subRect:CGRect) -> UIImage {

    UIGraphicsBeginImageContextWithOptions(subRect.size, YES, 0);

    let ctx = UIGraphicsGetCurrentContext();

    let contextOrigin = CGPointMake(-subRect.origin.x, subRect.size.height+subRect.origin.y-image.size.height); // Translates coordinates into Core Graphics space

    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -subRect.size.height);

    CGContextDrawImage(ctx, CGRectMake(contextOrigin.x, contextOrigin.y, image.size.width, image.size.height), image.CGImage);

    let img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;

}