2016-04-15 225 views
2

到目前爲止,在我的嘗試中,我可以在普通圖像上繪製線條,就像創建我自己的CGRect大小的簡單上下文並在其上畫線。我看到的所有教程都是如何繪製一個創建的x * y大小的圖像上下文。但是我想在已經存在的圖像上下文中畫一條狗的照片,並製作一些圖紙。但到目前爲止,我沒有得到我期待的結果。這是我測試的代碼,沒有分配圖像,我可以得到一個線條畫。但是通過導入圖片,我沒有在圖片上獲得所需的線條。如何在圖像上繪製線條/繪畫?

let myImage = UIImage(named: "hqdefault.jpg")! 
let myRGBA = RGBAImage(image: myImage)! 

UIGraphicsBeginImageContextWithOptions(CGSize(width: rgbaImage.width, height: rgbaImage.height), false, 0) 
let context:CGContextRef = UIGraphicsGetCurrentContext()! 
CGContextMoveToPoint(context, CGFloat(100.0), CGFloat(100.0)) 
CGContextAddLineToPoint(context, CGFloat(150.0), CGFloat(150.0)) 

CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor) 
CGContextStrokePath(context) 

let image = UIGraphicsGetImageFromCurrentImageContext() 

CGContextRestoreState(context) 
UIGraphicsEndImageContext() 
//: Return image 
let view = UIImageView.init(image: image) 
view.setNeedsDisplay() 

這些是我寫的在圖像中繪製一條線並返回其上下文的幾行。我無法選擇導入的圖片上下文,或者如果我嘗試繪製線條,因爲它最終返回零。到目前爲止,我無法弄清楚我的錯誤。你可以建議如何在圖像視圖中的圖片上畫一條簡單的線條嗎?

回答

3

您能否提供如何繪製簡單的線條上的圖片在圖像視圖

肯定。創建一個圖像上下文。將圖像視圖的圖像繪製到上下文中。在上下文中繪製線條。從上下文中提取結果圖像並關閉上下文。將提取的圖像分配給圖像視圖。

實施例:

let im = self.iv.image! // iv is the image view 
    UIGraphicsBeginImageContextWithOptions(im.size, true, 0) 
    im.drawAtPoint(CGPointMake(0,0)) 
    let p = UIBezierPath() 
    p.moveToPoint(CGPointMake(CGFloat(100.0), CGFloat(100.0))) 
    p.addLineToPoint(CGPointMake(CGFloat(150.0), CGFloat(150.0))) 
    p.stroke() 
    self.iv.image = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 

之前:

enter image description here

後:

enter image description here

在第二圖像中,請注意,從(100,100)延伸的線( 150,150)。

+0

如果可以,我可以看看上面的示例代碼嗎?我試圖將圖像繪製到上下文中,使用 CGContextDrawImage(context,CGRect(x:0,y:0,width:myRGBA!.width,height:myRGBA!.height),ciImage) 但我得到停留在將ciImage轉換爲CGImage錯誤。希望我可以檢查上面的代碼? –

+0

我在下面的代碼中嘗試了drawInRect,然後使用CGContextDrawImage myImage,將CGContextDrawImage(context,CGRect(x:0,y:0,width:myRGBA!.width,myRGBA!.height),cgImageMade) drawInRect(CGRect(x:0,y:0,width:300,height:300),blendMode:CGBlendMode.Clear,alpha:1.0) 添加CGContextMove和CGContextAdd方法後,我將結果通過 var result:UIImage = UIGraphicsGetImageFromCurrentImageContext(); 但我得到零結果。 –

+0

「但我被困在ciImage轉換爲CGImage錯誤」這聽起來像你的問題。這個故事中你不應該有任何CIImage。你也不需要轉換成CGImage。 UIImage可以直接將自己繪製到圖形上下文中。 – matt