2017-08-25 17 views
-1

私は単純な描画プログラムをUIView(以下のコードのキャンバス)に描画しています。これは正常に動作します。消しゴムのような行を描くSwift3

今、私はこれらの線を消しゴムのようにこすることができるようにしたい。

キャンバスビューの背後にバックグラウンドイメージがあるため、ユーザーが変更できるので、バックグラウンドイメージをビューに描画すると、半分に変更できるため、バックグラウンドイメージを描画することもできないため、絵を描く方法。

既存のすべてのパスで消しゴムのように機能するパスを描画するにはどうすればよいですか?

は、ここに私の現在の描画コード

func drawLine(fromPoint start: CGPoint, toPoint end:CGPoint, color: UIColor, width: CGFloat, canvas: UIView) 
{ 
    let line = CAShapeLayer() 
    let linePath = UIBezierPath() 

    linePath.move(to: start) 
    linePath.addLine(to: end) 

    line.path = linePath.cgPath 
    line.strokeColor = color.cgColor 
    line.lineWidth = width 
    line.lineJoin = kCALineJoinRound 

    canvas.layer.addSublayer(line) 
} 

感謝です!

答えて

0

私はこれを考え出した

linePath.stroke(with: CGBlendMode.clear, alpha: 1.0) 
+0

私が上記の機能で使用する方法を示すことはできますか? tと何を設定するかについてはかなり確かに注意してください –

+0

ここで何か助けてくださいAbdelahad?私はあなたがここに書いたものは私が必要とするものに近いと思うが、私はそれを理解することはできない。それをもっと明確にするためにできることはありますか?ありがとう。 –

0

OK描画するための消去のためのモードCGBlendMode.clearと脳卒中と CGBlendMode.normalを使用することができます。パスを作成するためにCAShapeLayersを使用する代わりに、グラフィックスコンテキストで描画する必要があります。ここに私が今使っているコードがあります。キャンバスはUIViewではなくUIImageViewになりました。

func drawLine(fromPoint start: CGPoint, toPoint end:CGPoint, color: UIColor, width: CGFloat) 
{ 
    //get the current graphics context based on the frame of the view I want to draw in. 
    UIGraphicsBeginImageContextWithOptions(canvas.frame.size, false, 0.0); 

    //draw the current image (all the lines drawn so far) into the view so we aren't just drawing new lines each time and losing the old ones 
    canvas.image?.draw(in: canvas.bounds) 
    //FYI - canvas is defined at the top of the class as a UIImageView 

    //get the current graphics context 
    if let context = UIGraphicsGetCurrentContext() 
    { 
     //set line color and other properties 
     context.setLineWidth(width) 
     context.setStrokeColor(color.cgColor) 
     context.setLineCap(CGLineCap.round) 

     //add the line itself 
     context.move(to: start) 
     context.addLine(to: end) 

     //this is a check to see if the last component of the color is 0 which means the color is transparent, if it is, we use CGBlendMode.clear which acts like an eraser. you could have a toggle for this instead if you like but I decided to set the color to one without alpha as the way of setting the eraser. 
     if(currentColor.cgColor.components?.count == 4 && currentColor.cgColor.components?.last == 0) 
     { 
      context.setBlendMode(CGBlendMode.clear) 
     } 
     else 
     { 
      context.setBlendMode(CGBlendMode.normal) 
     } 


     //stroke the path so it actually appears 
     context.strokePath() 

     //set the canvas image to the new image we just created 
     canvas.image = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 

    } 


} 
関連する問題