Skip to content

Instantly share code, notes, and snippets.

@BrunoVT1992
Created July 27, 2017 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrunoVT1992/6b341d61ca9a7e6354f55f3e77b9fd69 to your computer and use it in GitHub Desktop.
Save BrunoVT1992/6b341d61ca9a7e6354f55f3e77b9fd69 to your computer and use it in GitHub Desktop.
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