C4 saving part of an image

后端 未结 3 548
执笔经年
执笔经年 2021-01-27 01:53

Hei, I went through the example for saving images and afterwards I wanted to save only a part of the screen. I managed to save the part starting at the upper left corner of the

3条回答
  •  感动是毒
    2021-01-27 02:39

    a little modification to Travis' answer makes it independent from the image but dependent on the canvas origin:

    -(C4Image *)cropImage:(C4Image *)originalImage withOrigin:(CGPoint)origin toArea:(CGRect)rect{
        //grab the image scale
        CGFloat scale = originalImage.UIImage.scale;
    
        //begin an image context
        UIGraphicsBeginImageContextWithOptions(rect.size, NO, scale);
    
        //create a new context ref
        CGContextRef c = UIGraphicsGetCurrentContext();
    
        //shift BACKWARDS in both directions because this moves the image
        //the area to crop shifts INTO: (0, 0, rect.size.width, rect.size.height)
        CGContextTranslateCTM(c, origin.x-rect.origin.x, origin.y-rect.origin.y);
    
        //render the original image into the context
        [originalImage renderInContext:c];
    
        //grab a UIImage from the context
        UIImage *newUIImage = UIGraphicsGetImageFromCurrentImageContext();
    
        //end the image context
        UIGraphicsEndImageContext();
    
        //create a new C4Image
        C4Image *newImage = [C4Image imageWithUIImage:newUIImage];
    
        //return the new image
        return newImage;
    }
    

提交回复
热议问题