我是 android 的新手,我正在制作一个简单的应用程序,在其中我从图库中选择一个图像,在图像上绘制一个矩形,用户可以在图像上的任何位置拖动该矩形并动态调整矩形的大小。
到目前为止,我的代码可以从图库中加载图像并在图像上绘制一个矩形。但我不知道如何使矩形可动态拖动。
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
Bitmap bMap = BitmapFactory.decodeFile(picturePath);
bMap = bMap.copy(Bitmap.Config.ARGB_8888 , true);
float width = imageView.getWidth();
float height = imageView.getHeight();
Canvas canvas = new Canvas(bMap);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(4);
paint.setColor(Color.RED);
canvas.drawRect(width/2+60, height/2-20, width/2-60, height/2+20, paint);
imageView.setImageBitmap(bMap);
}
}
}
我想要的输出类似于上图。用户可以调整红色矩形的大小并拖动,然后保存图像。