我在Android上使用位图,在使用4点选择位图上的区域时遇到问题。并非所有的4点都适合我。在某些情况下,结果只是一个空白位图而不是裁剪位图(如图中所示),并且logcat中没有任何错误(甚至是内存错误)。 这是我用来进行转换的基本代码。
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.widget.ImageView;
public class CropImageActivity extends Activity {
private ImageView mCroppedImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.crop);
setupViews();
doCropping();
}
private void doCropping() {
Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample);
//target size
int bitmapWidth = 400;
int bitmapHeight = 400;
Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
//This is one of bad quadangle.
points[0] = 0; //top-left.x
points[1] = 0; //top-left.y
points[2] = 230; //top-right.x
points[3] = 100; //top-right.y
points[4] = 350; //bottom-right.x
points[5] = 350; //bottom-right.y
points[6] = 0; //bottom-left.x
points[7] = 350; //bottom-left.y
float[] src = new float[]{
points[0], points[1],
points[2], points[3],
points[4], points[5],
points[6], points[7]
};
float[] dsc = new float[]{
0, 0,
bitmapWidth, 0,
bitmapWidth, bitmapHeight,
0, bitmapHeight
};
Matrix matrix = new Matrix();
boolean transformResult = matrix.setPolyToPoly(src, 0, dsc, 0, 4);
canvas.drawBitmap(srcBitmap, matrix, null);
mCroppedImageView.setImageBitmap(bitmap);
}
private void setupViews() {
mCroppedImageView = (ImageView) findViewById(R.id.croppedImageView);
}
}
那么,4点坐标会影响画布绘制还是矩阵变换?任何帮助表示赞赏。
谢谢
答案 0 :(得分:2)
最后,我使用OpenCV解决了我的问题。感谢this question中的答案!似乎Matrix.setPolyToPoly
并不适用于所有情况。
答案 1 :(得分:0)
一切都更简单..
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Matrix matrix = new Matrix();
matrix.setPolyToPoly(src, 0, dst, 0, 4);
canvas.setMatrix(matrix);
canvas.drawBitmap(bit,0,0,null );
}
答案 2 :(得分:0)
您看到的错误不在Matrix.setPolyToPloy
中,而在CPU栅格化中。要解决此问题,您可以简单地创建一个新的转换后的Bitmap
而不使用Canvas
,然后裁剪Bitmap
以获得所需的结果。