Free draw view for Xamarin iOS
using CoreGraphics; | |
using Foundation; | |
using UIKit; | |
namespace iOS | |
{ | |
public class FreeDrawUIView : UIView | |
{ | |
UIBezierPath _path; | |
public UIImage Image { get; private set; } | |
public FreeDrawUIView() | |
{ | |
_path = new UIBezierPath | |
{ | |
LineWidth = 10 | |
}; | |
Image = new UIImage(); | |
MultipleTouchEnabled = false; | |
} | |
public override void Draw(CGRect rect) | |
{ | |
base.Draw(rect); | |
Image.DrawAsPatternInRect(rect); | |
_path.Stroke(); | |
} | |
public override void TouchesBegan(NSSet touches, UIEvent evt) | |
{ | |
base.TouchesBegan(touches, evt); | |
var touch = (UITouch)touches.AnyObject; | |
var point = touch.LocationInView(this); | |
_path.MoveTo(point); | |
} | |
public override void TouchesMoved(NSSet touches, UIEvent evt) | |
{ | |
base.TouchesMoved(touches, evt); | |
var touch = (UITouch)touches.AnyObject; | |
var point = touch.LocationInView(this); | |
_path.AddLineTo(point); | |
SetNeedsDisplay(); | |
} | |
public override void TouchesEnded(NSSet touches, UIEvent evt) | |
{ | |
base.TouchesEnded(touches, evt); | |
var touch = (UITouch)touches.AnyObject; | |
var point = touch.LocationInView(this); | |
_path.AddLineTo(point); | |
DrawBitmap(); | |
SetNeedsDisplay(); | |
_path.RemoveAllPoints(); | |
} | |
public override void TouchesCancelled(NSSet touches, UIEvent evt) | |
{ | |
base.TouchesCancelled(touches, evt); | |
TouchesEnded(touches, evt); | |
} | |
void DrawBitmap() | |
{ | |
UIGraphics.BeginImageContextWithOptions(Bounds.Size, true, 0); | |
UIColor.Black.SetStroke(); | |
if (Image != null) | |
{ | |
var rectPath = UIBezierPath.FromRect(Bounds); | |
UIColor.White.SetFill(); | |
rectPath.Fill(); | |
} | |
Image.Draw(CGPoint.Empty); | |
_path.Stroke(); | |
Image = UIGraphics.GetImageFromCurrentImageContext(); | |
UIGraphics.EndImageContext(); | |
} | |
public void Clear() | |
{ | |
_path.RemoveAllPoints(); | |
Image = new UIImage(); | |
SetNeedsDisplay(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment