2011-03-24 117 views
17

我有一個UIView,我通過典型的UIGraphicsBeginImageContextWithOptions方法呈現給UIImage,使用2.0的縮放比例,因此圖像輸出將始終是屏幕上顯示內容的「視網膜顯示」版本,無論用戶的實際屏幕分辨率。UIView的Uiimage:高於屏幕分辨率?

我渲染的UIView包含圖像和文本(UIImages和UILabels)。圖像以全分辨率顯示在呈現的UIImage中,並且看起來很棒。但是UILabel似乎已經以1.0的比例被柵格化,然後被升級到2.0,導致文本模糊。

有沒有什麼我做錯了,或者有什麼方法讓文本在更高的級別上呈現出漂亮和清晰?或者有什麼方法可以做到這一點,而不是使用UIGraphicsBeginImageContextWithOptions的縮放參數來獲得更好的結果?謝謝!

回答

9

解決方法是在繪製標籤之前將標籤的contentsScale更改爲2,然後立即將其設置回來。我只是編寫了一個項目來驗證它,它的工作很好,在正常的視網膜電話(模擬器)中製作了一個2倍的圖像。 [如果你有一個公共的地方,我可以把它讓我知道。]

編輯:擴展的代碼走子視圖和任何容器UIViews到設置/取消規模

- (IBAction)snapShot:(id)sender 
{ 
    [self changeScaleforView:snapView scale:2]; 

    UIGraphicsBeginImageContextWithOptions(snapView.bounds.size, snapView.opaque, 2); 
    [snapView.layer renderInContext:UIGraphicsGetCurrentContext()]; 

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); 

    UIGraphicsEndImageContext(); 

    imageDisplay.image = img; // contentsScale 
    imageDisplay.contentMode = UIViewContentModeScaleAspectFit; 

    [self changeScaleforView:snapView scale:1]; 
} 

- (void)changeScaleforView:(UIView *)aView scale:(CGFloat)scale 
{ 
    [aView.subviews enumerateObjectsUsingBlock:^void(UIView *v, NSUInteger idx, BOOL *stop) 
     { 
      if([v isKindOfClass:[UILabel class]]) { 
       v.layer.contentsScale = scale; 
      } else 
      if([v isKindOfClass:[UIImageView class]]) { 
       // labels and images 
       // v.layer.contentsScale = scale; won't work 

       // if the image is not "@2x", you could subclass UIImageView and set the name of the @2x 
       // on it as a property, then here you would set this imageNamed as the image, then undo it later 
      } else 
      if([v isMemberOfClass:[UIView class]]) { 
       // container view 
       [self changeScaleforView:v scale:scale]; 
      }  
     } ]; 
} 
+0

這可以工作,但是如果你想捕獲一個UITableView,單獨改變每個圖層是一種痛苦。沒有辦法改變它的所有子視圖遞歸? – charliehorse55 2012-07-28 22:20:26

+1

那麼,沒有我知道的單一命令,但注意擴展的代碼會緩解並完成大部分工作。如果您沒有將imageViews設置爲2x圖像(對於非視網膜顯示器來說工作正常,在渲染時使系統工作更多一點,您將不得不做一些特別的事情。 – 2012-07-31 00:45:34

2

嘗試渲染到與雙大小的圖像,然後創建縮放的圖像:

UIGraphicsBeginImageContextWithOptions(size, NO, 1.0); 
// Do stuff 
UImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

newImage=[UIImage imageWithCGImage:[newImage CGImage] scale:2.0 orientation:UIImageOrientationUp]; 

其中: 尺寸= realSize *規模;

+0

不知道我理解你'再說一遍。我沒有和我一起工作的CGImage,我有一個UIView,然後我將它渲染成一個UIImage ... – DanM 2011-03-28 12:19:17

+0

已編輯。它應該做你想做的。 – ssteinberg 2011-03-28 12:40:17

+1

是不是隻是按比例*所有* up?那麼現在文本*和*圖片都會模糊不清了? – DanM 2011-03-29 14:35:31

0

我一直在與textview的上下文中的許多相同的古怪與PDF渲染掙扎。我發現構成視圖的CALayer對象上有一些記錄的屬性。也許設置相關(子)層的柵格化比例有助於。