我创建了一个如下所示的画布视图。当我将它应用于一个新项目时,它可以正常工作,但当我把它放入我的真实项目时,我无法画出实线。它总是被破灭(如下图所示)。第一次,我认为这是一个问题,因为我推了太多的屏幕,直到这个可绘制。但是我每次推入新视图时都试图禁用上一个视图的UserInteraction,但它没有用。请帮忙!
public class CanvasView : UIView
{
public CanvasView (CGRect frame) : base(frame)
{
this.drawPath = new CGPath();
BackgroundColor = UIColor.White;
}
private CGPoint touchLocation;
private CGPoint previousTouchLocation;
private CGPath drawPath;
private bool fingerDraw;
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
Layer.BorderWidth = 0.5f;
Layer.BorderColor = UIColor.FromRGB (146, 146, 146).CGColor;
}
public override void TouchesBegan (NSSet touches, UIEvent evt)
{
base.TouchesBegan (touches, evt);
UITouch touch = touches.AnyObject as UITouch;
this.fingerDraw = true;
this.touchLocation = touch.LocationInView(this);
this.previousTouchLocation = touch.PreviousLocationInView(this);
this.SetNeedsDisplay();
}
public override void TouchesMoved (NSSet touches, UIEvent evt)
{
base.TouchesMoved (touches, evt);
UITouch touch = touches.AnyObject as UITouch;
this.touchLocation = touch.LocationInView(this);
this.previousTouchLocation = touch.PreviousLocationInView(this);
this.SetNeedsDisplay();
}
public override void TouchesEnded (NSSet touches, UIEvent evt)
{
base.TouchesEnded (touches, evt);
var alert = new UIAlertView () {
Message = "Xui"
};
alert.AddButton("OK");
alert.Show();
}
public override void Draw (CGRect rect)
{
base.Draw (rect);
if (this.fingerDraw)
{
using (CGContext context = UIGraphics.GetCurrentContext())
{
context.SetStrokeColor(UIColor.Black.CGColor);
context.SetLineWidth(1.5f);
context.SetLineJoin(CGLineJoin.Round);
context.SetLineCap(CGLineCap.Round);
this.drawPath.MoveToPoint(this.previousTouchLocation);
this.drawPath.AddLineToPoint(this.touchLocation);
context.AddPath(this.drawPath);
context.DrawPath(CGPathDrawingMode.Stroke);
}
}
}
}
答案 0 :(得分:0)
我认为问题不在于TouchesMoved
,而在于你的绘图逻辑。当你打电话给SetNeedsDisplay()
时,它并不意味着“现在画画”,它意味着“我有需要画出的变化,所以要亲爱的,尽可能吸引我。”这意味着在处理绘图之前会有更多的触摸。
在调用Draw
之前,您必须保持前一个点相同,否则您必须将这些点放入缓冲区并同时绘制所有点。我会做第一个,因为它更简单。