效果如下:
理解:Xfermode的16总模式如图
第一步:
package com.rong.activity;
import com.rong.test.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
/**
* 改变图片颜色的自定义View
* @author 徐荣
*
*/
public class ChangeImageColorView extends View {
Paint mPaint;
PorterDuffXfermode xfermode;
Bitmap bitmap;
int mBitWidth;
int mBitHeight;
int width;
int height;
Rect srcRect;
Rect dstRect;
RectF mRect;
int i=0;
public ChangeImageColorView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
private void initView() {
// 初始化画笔
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.BLUE);
// 设置Xfermode
xfermode = new PorterDuffXfermode(Mode.SRC_IN);
// 获取图片源
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.robot);
mBitWidth = bitmap.getWidth();
mBitHeight = bitmap.getHeight();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
//获取控件的宽高
width = w;
height = h;
srcRect = new Rect(0, 0, width, height);
dstRect = new Rect(0, 0, width, height);
mRect = new RectF(0, 0, width, height);
i=width;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//相当于PS的新建图层
int num = canvas.saveLayer(0, 0, width, height, mPaint, Canvas.ALL_SAVE_FLAG);
//绘制图片
canvas.drawBitmap(bitmap, srcRect, dstRect, mPaint);
//设置图片混合模式
mPaint.setXfermode(xfermode);
//绘制动态区域
canvas.drawRect(mRect, mPaint);
//恢复混合模式
mPaint.setXfermode(null);
//合并图层
canvas.restoreToCount(num);
//更改区域的位置
i = i - 1;
mRect.top = i;
if (i == 0) {
i = width;
}
//刷新UI,他会调用onDraw方法
invalidate();
}
}
第二步
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_touchlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical" >
<com.rong.activity.ChangeImageColorView
android:id="@+id/main_percentview"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true" />
</RelativeLayout>