首先看一下效果图,有一个可以在背景上移动的吸管,按钮的文字颜色随着吸取的颜色不同而变化。
下面来看看代码,这是自定义的View
初始化吸管的图片和背景图片
private void init() {
bitmapTemp = BitmapFactory.decodeResource(getResources(),
R.drawable.bg);
mRightPaint = new Paint();
mRightPaint.setStyle(Paint.Style.FILL);
mRightPaint.setStrokeWidth(1);
mRightColors = new int[3];
mRightColors[0] = Color.WHITE;
mRightColors[2] = Color.BLACK;
mBitmapPaint = new Paint();
mLeftBitmap = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.icon_pickcolor);//吸管的图片
mLeftBitmap2 = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.icon_pickcolor);
mLeftBitmapRadius = mLeftBitmap.getWidth() / 2;
mLeftSelectPoint = new PointF(0, 0);
newWidgth = BitmapFactory.decodeResource(getResources(),
R.drawable.bg).getWidth();//背景图片
newHeigh = BitmapFactory.decodeResource(getResources(),
R.drawable.icon_pickcolor).getHeight();
}
把吸管的图片画上去<span style="white-space:pre"> </span>
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(getGradual(), null, new Rect(0, 0, LEFT_WIDTH,
mHeight), mBitmapPaint);
// 右边
// 两个图标
if (mLeftMove) {
canvas.drawBitmap(mLeftBitmap, mLeftSelectPoint.x
- mLeftBitmapRadius,
mLeftSelectPoint.y - mLeftBitmapRadius, mBitmapPaint);
} else {
try {
canvas.drawBitmap(mLeftBitmap2, mLeftSelectPoint.x
- mLeftBitmapRadius, mLeftSelectPoint.y
- mLeftBitmapRadius, mBitmapPaint);
} catch (Exception e) {
// TODO: handle exception
}
}
}
获取根据方法<span style="font-family: Arial, Helvetica, sans-serif;">getPixel</span>
获取图片的颜色
private int getLeftColor(float x, float y) {
Bitmap temp = getGradual();
// 为了防止越界
int intX = (int) x;
int intY = (int) y;
if (intX < 0)
intX = 0;
if (intY < 0)
intY = 0;
if (intX >= temp.getWidth()) {
intX = temp.getWidth() - 1;
}
if (intY >= temp.getHeight()) {
intY = temp.getHeight() - 1;
}
return temp.getPixel(intX, intY);
有更好的方法,请大家多多分享,附Dmo下载地址:
http://download.csdn.net/detail/hzcy223/7759447