Skip to content

Instantly share code, notes, and snippets.

@BrunoVT1992
Created July 27, 2017 07:38
Show Gist options
  • Save BrunoVT1992/0b6f3bbf46deb165f74a863012d7d145 to your computer and use it in GitHub Desktop.
Save BrunoVT1992/0b6f3bbf46deb165f74a863012d7d145 to your computer and use it in GitHub Desktop.
Free draw view for Xamarin Android
using Android.Content;
using Android.Graphics;
using Android.Util;
using Android.Views;
namespace Droid
{
public class FreeDrawView : View
{
Path _drawPath;
Paint _drawPaint;
Paint _canvasPaint;
Canvas _drawCanvas;
Bitmap _canvasBitmap;
Color _currentLineColor;
float _penWidth;
public Bitmap Image
{
get
{
return GetDrawingCache(false);
}
}
public FreeDrawView(Context context)
: base(context)
{
Init();
}
public FreeDrawView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
Init();
}
public FreeDrawView(Context context, IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle)
{
Init();
}
void Init()
{
_currentLineColor = Color.Black;
_penWidth = 8.0f;
_drawPath = new Path();
_drawPaint = new Paint
{
Color = _currentLineColor,
AntiAlias = true,
StrokeWidth = _penWidth
};
_drawPaint.SetStyle(Paint.Style.Stroke);
_drawPaint.StrokeJoin = Paint.Join.Round;
_drawPaint.StrokeCap = Paint.Cap.Round;
_canvasPaint = new Paint
{
Dither = true
};
DrawingCacheEnabled = true;
DrawingCacheBackgroundColor = Color.White;
}
protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
{
base.OnSizeChanged(w, h, oldw, oldh);
_canvasBitmap = Bitmap.CreateBitmap(w, h, Bitmap.Config.Argb8888);
_drawCanvas = new Canvas(_canvasBitmap);
}
protected override void OnDraw(Canvas canvas)
{
base.OnDraw(canvas);
_drawPaint.Color = _currentLineColor;
canvas.DrawBitmap(_canvasBitmap, 0, 0, _canvasPaint);
canvas.DrawPath(_drawPath, _drawPaint);
}
public override bool OnTouchEvent(MotionEvent e)
{
var touchX = e.GetX();
var touchY = e.GetY();
switch (e.Action)
{
case MotionEventActions.Down:
_drawPath.MoveTo(touchX, touchY);
break;
case MotionEventActions.Move:
_drawPath.LineTo(touchX, touchY);
break;
case MotionEventActions.Up:
_drawCanvas.DrawPath(_drawPath, _drawPaint);
_drawPath.Reset();
break;
default:
return false;
}
Invalidate();
return true;
}
public void Clear()
{
_drawCanvas = new Canvas(_canvasBitmap);
Invalidate();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment