2010-11-16 49 views
12

我正在截取我的應用程序。我能夠截取屏幕截圖。帶參數的UIGraphicsBeginImageContext

現在我想通過指定x和y座標截取屏幕截圖。那可能嗎?

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

回答

18
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(); 
+0

感謝您的答覆...是否有任何方式來改變它的高度和寬度.. – user198725878 2010-11-16 13:26:49

+0

@barbgal:使用CGContextScaleCTM來調整大小。此外,您可能需要更小的上下文(將參數更改爲UIGraphicsBeginImageContext)。 – kennytm 2010-11-16 13:31:48

+2

@Barbgal:No.'CGSize size = self.view.bounds.size; UIGraphicsBeginImageContext(CGSizeMake(size.width,size.height-40)); CGContextRef c = UIGraphicsGetCurrentContext();' – kennytm 2010-11-16 13:40:38

2

如果您使用的是較新的視網膜顯示設備,你的代碼應該在決議通過UIGraphicsBeginImageContextWithOptions代替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(); 

這會使視網膜顯示圖像內容。

0

就做這樣的事情,比那些複雜的計算

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

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

    UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); 

    UIGraphicsEndImageContext(); 

    return result; 
} 
0

這裏比較容易的方式是斯威夫特版本

//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 

} 
0

迅速版

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)