![](/img/trans.png)
[英]How to generate a dynamic light/dark mode UIImage from Core Graphics?
[英]How to create a UIImage from the current graphics context?
我想從當前的圖形上下文創建一個UIImage對象。 更具體地說,我的用例是用戶可以繪制線條的視圖。 他們可以逐步繪制。 完成后,我想創建一個UIImage來代表他們的繪圖。
這是drawRect:現在對我來說是這樣的:
- (void)drawRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSaveGState(c);
CGContextSetStrokeColorWithColor(c, [UIColor blackColor].CGColor);
CGContextSetLineWidth(c,1.5f);
for(CFIndex i = 0; i < CFArrayGetCount(_pathArray); i++)
{
CGPathRef path = CFArrayGetValueAtIndex(_pathArray, i);
CGContextAddPath(c, path);
}
CGContextStrokePath(c);
CGContextRestoreGState(c);
}
...其中_pathArray的類型為CFArrayRef,並且每次調用touchesEnded:時都會填充。 另請注意,drawRect:可以在用戶繪制時多次調用。
用戶完成后,我想創建一個表示圖形上下文的UIImage對象。 有關如何做到這一點的任何建議?
您需要先設置圖形上下文:
UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
如果你需要保持image
,一定要保留它!
編輯:如果要將drawRect的輸出保存到圖像,只需使用UIGraphicsBeginImageContext
創建位圖上下文,並使用新的上下文綁定調用drawRect函數。 這比在drawRect中保存您正在使用的CGContextRef更容易 - 因為該上下文可能沒有與之關聯的位圖信息。
UIGraphicsBeginImageContext(view.bounds.size);
[view drawRect: [myView bounds]];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
您也可以使用Kelvin提到的方法。 如果您想從更復雜的視圖(如UIWebView)創建圖像,他的方法會更快。 繪制視圖的圖層不需要刷新圖層,只需要將圖像數據從一個緩沖區移動到另一個緩沖區!
Swift版本
func createImage(from view: UIView) -> UIImage {
UIGraphicsBeginImageContext(view.bounds.size)
view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let viewImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return viewImage
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.