UIGraphicsBeginImageContext with parameters

南楼画角 提交于 2019-12-05 15:05:14

问题


I am taking a screenshot in my application. I am able to take the screenshot.

Now I want to take the screenshot by specifying the x and y coordinate. Is that possible?

UIGraphicsBeginImageContext( self.view.bounds.size );
[self.view.layer renderInContext:UIGraphicsGetCurrentContext(  )];
UIImage* aImage = UIGraphicsGetImageFromCurrentImageContext(  );

回答1:


UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(c, 0, -40);    // <-- shift everything up by 40px when drawing.
[self.view.layer renderInContext:c];
UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();



回答2:


If you're using a newer retina display device, your code should factor in the resolution by using UIGraphicsBeginImageContextWithOptions instead of UIGraphicsBeginImageContext:

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,YES,2.0);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(c, 0, -40);    // <-- shift everything up by 40px when drawing.
[self.view.layer renderInContext:c];
UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

This will render the retina display image context.




回答3:


Just do something like this, way easier than all those complex calculations

+ (UIImage *)imageWithView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions([view bounds].size, NO, [[UIScreen mainScreen] scale]);

    [[view layer] renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return result;
}



回答4:


Here is Swift version

//Capture Screen
func capture()->UIImage {

    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, UIScreen.mainScreen().scale)
    self.view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image

}



回答5:


swift version

    UIGraphicsBeginImageContext(self.view.bounds.size)
    let image: CGContextRef = UIGraphicsGetCurrentContext()!
    CGContextTranslateCTM(image, 0, -40)
    // <-- shift everything up by 40px when drawing.
    self.view.layer.renderInContext(image)
    let viewImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil)


来源:https://stackoverflow.com/questions/4194388/uigraphicsbeginimagecontext-with-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!