以下是一个使用setPolyToPoly()方法来裁剪图像的示例代码:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class CropImageView extends View {
private Bitmap mBitmap;
private Matrix mMatrix;
private int mImageWidth, mImageHeight;
private PointF[] mPolyPoints;
private int mPolyPointCount;
public CropImageView(Context context) {
super(context);
init();
}
public CropImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// 加载图像
mBitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.your_image)).getBitmap();
mImageWidth = mBitmap.getWidth();
mImageHeight = mBitmap.getHeight();
// 设置初始变换矩阵
mMatrix = new Matrix();
mMatrix.setTranslate(0, 0);
// 设置多边形顶点
mPolyPoints = new PointF[4];
mPolyPointCount = 0;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制图像
canvas.drawBitmap(mBitmap, mMatrix, null);
// 绘制多边形边界线
if (mPolyPointCount > 0) {
for (int i = 0; i < mPolyPointCount - 1; i++) {
canvas.drawLine(mPolyPoints[i].x, mPolyPoints[i].y,
mPolyPoints[i + 1].x, mPolyPoints[i + 1].y, null);
}
// 绘制多边形最后一条边
canvas.drawLine(mPolyPoints[mPolyPointCount - 1].x, mPolyPoints[mPolyPointCount - 1].y,
mPolyPoints[0].x, mPolyPoints[0].y, null);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 添加顶点
if (mPolyPointCount < 4) {
mPolyPoints[mPolyPointCount] = new PointF(event.getX(), event.getY());
mPolyPointCount++;
}
break;
case MotionEvent.ACTION_MOVE:
// 移动顶点
if (mPolyPointCount > 0) {
mPolyPoints[mPolyPointCount - 1].set(event.getX(), event.getY());
}
break;
case MotionEvent.ACTION_UP:
// 完成多边形裁剪
if (mPolyPointCount == 4) {
cropImage();
}
break;
}
invalidate();
return true;
}
private void cropImage() {
// 创建裁剪后的图像
Bitmap croppedBitmap = Bitmap.createBitmap(mImageWidth, mImageHeight, Bitmap.Config.ARGB_8888);
Canvas croppedCanvas = new Canvas(croppedBitmap);
// 设置裁剪区域
float[] src = new float[mPolyPointCount * 2];
float[] dst = new float[mPolyPointCount * 2];
for (int i = 0; i < mPolyPointCount; i++) {
src[i * 2] = mPolyPoints[i].x;
src[i * 2 + 1] = mPolyPoints[i].y;
dst[i * 2] = i * 100; // 设置裁剪后的图像顶点x坐标
dst[i * 2 + 1] = i * 100; // 设置裁剪后的图像顶点y坐标
}
Matrix polyMatrix = new Matrix();
polyMatrix.setPolyToPoly(src, 0, dst, 0, mPolyPointCount);
croppedCanvas.drawBitmap(mBitmap, polyMatrix, null);
// 使用裁剪后的图像
mBitmap = croppedBitmap;
mImageWidth = mBitmap.getWidth();
mImageHeight = mBitmap.getHeight();
// 重置多边形顶点
mPolyPointCount = 0;
}
}
请注意,此示例中的R.drawable.your_image应替换为您自己的图像资源