Matrix原理
Matrix詳解
-Matrix常用方法
setPolyToPoly
最多可以支持4個(gè)點(diǎn)粹排,這4個(gè)點(diǎn)通常為圖片的四個(gè)角挎狸,通過(guò)這四個(gè)角可將矩形變?yōu)槿魏涡螤?/p>
boolean setPolyToPoly (
float[] src, // 原始數(shù)組 src [x,y]路操,存儲(chǔ)內(nèi)容為一組點(diǎn)
int srcIndex, // 原始數(shù)組開始位置
float[] dst, // 目標(biāo)數(shù)組 dst [x,y]局劲,存儲(chǔ)內(nèi)容為一組點(diǎn)
int dstIndex, // 目標(biāo)數(shù)組開始位置
int pointCount) // 測(cè)控點(diǎn)的數(shù)量 取值范圍是: 0到4
代碼:
public class PolyView extends View {
private static final String TAG = "PolyView";
private Bitmap bitmap;
private Matrix matrix;
private int pointCount = 2; //setPolyToPoly最后一個(gè)參數(shù) 作為配置項(xiàng) 查看效果 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);
}
}
}
結(jié)果:
setRectToRect
boolean setRectToRect (RectF src, // 源區(qū)域
RectF dst, // 目標(biāo)區(qū)域
Matrix.ScaleToFit stf) // 縮放適配模式
代碼:
RectF src= new RectF(0, 0, mBitmap.getWidth(), mBitmap.getHeight() );
RectF dst = new RectF(0, 0, getWidth(), getHeight());
// 核心要點(diǎn)
mRectMatrix.setRectToRect(src,dst, Matrix.ScaleToFit.CENTER);
// 根據(jù)Matrix繪制一個(gè)變換后的圖片
canvas.drawBitmap(mBitmap, mRectMatrix, new Paint());