0

How do you create an image from another image in iOS swift?

E.g. If I had image (A) that was 1000px by 1000px. How would I create image (B) a 200px by 200px from the middle of image (A).

Peter Hornsby
  • 4,208
  • 1
  • 25
  • 44
woot586
  • 3,906
  • 10
  • 32
  • 40
  • You could use `imageByCroppingToBounds` in http://stackoverflow.com/a/28513086/1271826. – Rob Jan 20 '16 at 19:53

1 Answers1

0

You can do this easily in 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;

}
Hamish
  • 78,605
  • 19
  • 187
  • 280