我尝试从文件资源中绘制 ImageView。这是我的代码:
private Bitmap myBitmap;
private Bitmap mutableBitmap;
private Canvas canvas;
private Paint paint;
private ImageView img;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.layout_imagefullscreen);
paint = new Paint();
paint.setStrokeWidth(11);
paint.setColor(Color.YELLOW);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_LOW_PROFILE;
decorView.setSystemUiVisibility(uiOptions);
...
if (imageFileFullPathName != null) {
try {
File imgFile = new File (imageFileFullPathName);
if (imgFile.exists ()) {
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
mutableBitmap = myBitmap.copy(Bitmap.Config.ARGB_8888, true);
canvas = new Canvas(mutableBitmap);
img.setImageBitmap(mutableBitmap);
Matrix m = img.getImageMatrix();
canvas.setMatrix(m);
}
} catch (Exception e) {
e.printStackTrace ();
}
}
img.setOnTouchListener (new OnTouchListener() {
float startX, startY;
float stopX, stopY;
@Override
public boolean onTouch (View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
startY = event.getY();
Log.i("---> DOWN X", String.valueOf(startX));
Log.i("---> DOWN Y", String.valueOf(startY));
break;
case MotionEvent.ACTION_MOVE:
stopX = event.getRawX();
stopY = event.getRawY();
Log.i("---> MOVE X", String.valueOf(stopX));
Log.i("---> MOVE Y", String.valueOf(stopY));
canvas.drawLine(startX, startY, stopX, stopY, paint);
img.invalidate();
startX = event.getRawX();
startY = event.getRawY();
img.setImageBitmap(mutableBitmap);
break;
case MotionEvent.ACTION_UP:
stopX = event.getRawX();
stopY = event.getRawY();
Log.i("---> UP X", String.valueOf(stopX));
Log.i("---> UP Y", String.valueOf(stopY));
canvas.drawLine(startX, startY, stopX, stopY, paint);
img.invalidate();
break;
default:
break;
}
v.performClick();
return true;
}
});
}
}'
但是当我在 上移动手指时ImageView
,这条线并没有跟随我的手指,它只限制在屏幕的左上角。我也尝试更改getRawX()
为getX()
,但此问题仍然存在。我相信问题出在坐标变换上,但不知道如何解决。请帮忙,谢谢!
布局xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@color/Black">
<ImageView
android:id="@+id/imagefullscreenview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="@drawable/ic_launcher"/>
</LinearLayout>