2011-02-28 46 views
5

我正在嘗試將THIS問題與視網膜顯示器配合使用。以下是我如何解決如何使用UIGraphicsBeginImageContext的視網膜圖形。如何使用UIGraphicsBeginImageContextWithOptions?

if (UIGraphicsBeginImageContextWithOptions != NULL) 
{ 
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0.0f); 
} 
else 
{ 
    UIGraphicsBeginImageContext(self.view.bounds.size); 
} 

但是,當我使用它時,圖像看起來真的很大,並且不縮小以適應顯示。任何想法,我可以告訴它調整捕獲的圖像,以適應盒子? (請參考另一個問題來理解我的意思)。

回答

12

我已經寫了這段代碼來執行完全相同的事情在其他職位描述。 它適用於至少有iOS 3.1的任何iOS設備。

_launcherView是需要被拍到

CGFloat scale = 1.0; 
if([[UIScreen mainScreen]respondsToSelector:@selector(scale)]) {   
    CGFloat tmp = [[UIScreen mainScreen]scale]; 
    if (tmp > 1.5) { 
     scale = 2.0;  
    } 
} 

if(scale > 1.5) { 
    UIGraphicsBeginImageContextWithOptions(_launcherView.frame.size, NO, scale); 
} else { 
    UIGraphicsBeginImageContext(_launcherView.frame.size); 
} 

[_launcherView.layer renderInContext:UIGraphicsGetCurrentContext()]; 

UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

CGRect upRect = CGRectMake(0, 0, _launcherView.frame.size.width*scale, (diff - offset)*scale); 
CGImageRef imageRefUp = CGImageCreateWithImageInRect([screenshot CGImage], upRect); 
[self.screenshot1 setFrame:CGRectMake(0, 0, screenshot1.frame.size.width, diff - offset)]; 
[screenshot1 setContentMode:UIViewContentModeTop]; 
UIImage * img1 = [UIImage imageWithCGImage:imageRefUp]; 
[self.screenshot1 setBackgroundImage:img1 forState:UIControlStateNormal]; 
CGImageRelease(imageRefUp); 

CGRect downRect = CGRectMake(0, (diff - offset)*scale, _launcherView.frame.size.width*scale, (screenshot.size.height - diff + offset)*scale); 
CGImageRef imageRefDown = CGImageCreateWithImageInRect([screenshot CGImage], downRect); 
[self.screenshot2 setFrame:CGRectMake(0, screenshot1.frame.size.height , screenshot2.frame.size.width, _launcherView.frame.size.height - screenshot1.frame.size.height)]; 
[screenshot2 setContentMode:UIViewContentModeTop]; 
UIImage * img2 = [UIImage imageWithCGImage:imageRefDown]; 
[self.screenshot2 setBackgroundImage:img2 forState:UIControlStateNormal]; 
CGImageRelease(imageRefDown); 
+0

感謝的觀點!我無法訪問我的機器ATM,但我會盡快嘗試,並將其作爲答案接受。 – 2011-02-28 22:00:12

+0

如果您有任何問題,請告訴我,但我相信它會很容易地適應您的需求。 – MacTeo 2011-02-28 22:03:57

+0

工作得很好,謝謝!我只是想知道這是否可以用'UIImage'而不是'UIButton'完成。我不喜歡按鈕強制的「點擊」效果。 – 2011-03-01 04:06:32

-1
- (UIImage *)getNewimage{ 
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0); 
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; 
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return newImage; 
} 
+0

請添加更多關於您的答案的描述和/或信息,以及它如何解決問題,以便其他人可以輕鬆理解而不要求澄清 – koceeng 2017-02-28 04:47:19

相關問題