Matrix原理
Matrix详解
-Matrix常用方法

setPolyToPoly
最多可以支持4个点,这4个点通常为图片的四个角,通过这四个角可将矩形变为任何形状
boolean setPolyToPoly (
float[] src, // 原始数组 src [x,y],存储内容为一组点
int srcIndex, // 原始数组开始位置
float[] dst, // 目标数组 dst [x,y],存储内容为一组点
int dstIndex, // 目标数组开始位置
int pointCount) // 测控点的数量 取值范围是: 0到4


代码:
public class PolyView extends View {
private static final String TAG = "PolyView";
private Bitmap bitmap;
private Matrix matrix;
private int pointCount = 2; //setPolyToPoly最后一个参数 作为配置项 查看效果 0 1 2 3 4
private int triggerRadius = 100; //手指触摸半径
private float[] src = new float[8];
private float[] dst = new float[8];
private Paint pointPaint = new Paint();
public PolyView(Context context, AttributeSet attrs) {
super(context, attrs);
pointPaint.setAntiAlias(true);
pointPaint.setColor(Color.GRAY);
pointPaint.setStrokeWidth(20);
pointPaint.setStrokeCap(Paint.Cap.ROUND);
initBitmapAndMatrix();
}
private void initBitmapAndMatrix(){
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.def);
matrix = new Matrix();
float[] temp = new float[]{0,0, bitmap.getWidth()+0,0, bitmap.getWidth()+0,bitmap.getHeight()+0, 0,bitmap.getHeight()+0};
src = temp.clone();
dst = temp.clone();
matrix.setPolyToPoly(src,0,dst,0,pointCount);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_MOVE:
for (int i=0; i<pointCount*2; i+=2){
if (Math.abs(dst[i]-x) <= triggerRadius && Math.abs(dst[i+1] - y) <= triggerRadius){
dst[i] = event.getX();
dst[i+1] = event.getY();
resetMatrix();
}
}
break;
}
return true;
}
private void resetMatrix(){
matrix.reset();
matrix.setPolyToPoly(src,0,dst,0,pointCount);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(bitmap,matrix,null);
for (int i=0 ;i<pointCount*2; i+=2){
canvas.drawPoint(dst[i],dst[i+1],pointPaint);
}
}
}
结果:





setRectToRect
boolean setRectToRect (RectF src, // 源区域
RectF dst, // 目标区域
Matrix.ScaleToFit stf) // 缩放适配模式


代码:
RectF src= new RectF(0, 0, mBitmap.getWidth(), mBitmap.getHeight() );
RectF dst = new RectF(0, 0, getWidth(), getHeight());
// 核心要点
mRectMatrix.setRectToRect(src,dst, Matrix.ScaleToFit.CENTER);
// 根据Matrix绘制一个变换后的图片
canvas.drawBitmap(mBitmap, mRectMatrix, new Paint());

网友评论