how to crop image in to pieces programmatically

后端 未结 4 1353
天涯浪人
天涯浪人 2020-11-27 06:35

I need to divide an image into 9 pieces programmatically. Any suggestions on how to do this?

4条回答
  •  死守一世寂寞
    2020-11-27 07:09

    There are many ways to slice and dice an image but here is one. It uses Quartz to cut an image into 9 equal-sized fractions. Notice it does not handle rotated images (by that I mean images with imageOrientation!=0) but it should get you started:

    +(NSArray *)splitImageInTo9:(UIImage *)im{
        CGSize size = [im size];
        NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:9];
        for (int i=0;i<3;i++){
            for (int j=0;j<3;j++){
                CGRect portion = CGRectMake(i * size.width/3.0, j * size.height/3.0, size.width/3.0, size.height/3.0);
                UIGraphicsBeginImageContext(portion.size);
                CGContextRef context = UIGraphicsGetCurrentContext();
                CGContextScaleCTM(context, 1.0, -1.0);
                CGContextTranslateCTM(context, 0, -portion.size.height);
                CGContextTranslateCTM(context, -portion.origin.x, -portion.origin.y);
                CGContextDrawImage(context,CGRectMake(0.0, 0.0,size.width,  size.height), im.CGImage);
                [arr addObject:UIGraphicsGetImageFromCurrentImageContext()];
                UIGraphicsEndImageContext();
    
    
            }
        }
        return [arr autorelease];
    
    }
    

    The output will be an array of the 9 images each of size (with/3, height/3)

提交回复
热议问题