using System;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Util;
using Android.Views;
namespace Shared
{
///
/// 色板
///
public class ColorPicker : View
{
MyColorPickerView myColorPickerView {
get {
return AndroidView as MyColorPickerView;
}
set {
AndroidView = value;
}
}
///
/// Initializes a new instance of the class.
///
public ColorPicker()
{
myColorPickerView = new MyColorPickerView(Application.Activity,this);
}
string colorImagePath;
///
/// 色板图
///
/// The color image path.
public string ColorImagePath {
get {
return colorImagePath;
}
set {
colorImagePath = value;
Background (colorImagePath);
}
}
///
/// 颜色变化
///
public Action ColorChaged;
public class MyColorPickerView : Android.Views.View
{
Bitmap bitmapTemp;
View _view;
public MyColorPickerView(Context context, View view)
: base(context)
{
_view = view;
}
public override Android.Graphics.Drawables.Drawable Background
{
get
{
return base.Background;
}
set
{
base.Background = value;
bitmapTemp = drawableToBitmap(value);
}
}
static Bitmap drawableToBitmap(Drawable drawable)
{
if (drawable == null)
{
return null;
}
var bitmap = Bitmap.CreateBitmap(drawable.IntrinsicWidth,drawable.IntrinsicHeight,Bitmap.Config.Rgb565);
Canvas canvas = new Canvas(bitmap);
drawable.SetBounds(0, 0, drawable.IntrinsicWidth, drawable.IntrinsicHeight);
drawable.Draw(canvas);
return bitmap;
}
///
/// 重写点击事件
///
/// true, if touch event was oned, false otherwise.
/// E.
public override bool OnTouchEvent(MotionEvent e)
{
if (_view != null && _view.Enable)
{
_view.TouchEvent( e);
}
if (bitmapTemp != null && (_view as ColorPicker).ColorChaged != null)
{
int x = Math.Abs((int)(e.GetX() * bitmapTemp.Width / Width));
int y = Math.Abs((int)(e.GetY() * bitmapTemp.Height / Height));
if (bitmapTemp.Width <= x) {
x = bitmapTemp.Width - 1;
}
if (bitmapTemp.Height <= y) {
y = bitmapTemp.Height - 1;
}
var color = bitmapTemp.GetPixel(x,y);
(_view as ColorPicker).ColorChaged(_view, new byte[] { (byte)((color >> 16) & 0xFF), (byte)((color >> 8) & 0xFF), (byte)(color & 0xFF) });
//Shared.HDLUtils.WriteLine("ColorChaged color:" + color);
}
//return base.OnTouchEvent(e);
return true;//2019-09-09 改为 return true
}
}
}
}