Created
July 27, 2017 07:30
-
-
Save BrunoVT1992/6b341d61ca9a7e6354f55f3e77b9fd69 to your computer and use it in GitHub Desktop.
Free draw view for Xamarin iOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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