我需要实现一个揭开幕布显示一张图片的功能,一开始我用ImageView显示一张灰色的幕布(该幕布用指定要显示的图片构造大小),然后通过触屏事件(假设是DOWN)从指定要显示的图片切一块(默认指定是10×10像素),最后把切出来的作为源图,通过Canvas.drawBitmap(src,left,top,paint)画到幕布上,结果是画出来的图片位置与我在屏幕上点击的位置有偏移,其中left和top用的就是getX()和getY()的值,这是什么原因呢?
------解决方案--------------------
package com.zhutieju.openphoto;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
public class OpenPhotoActivity extends Activity {
Button previousBtn,nextBtn;
ImageView picture;
Cursor cursor;
String imageFilePath;
int fileColumn;
Bitmap pictureBmp,cloth;
Canvas canvas;
Paint paint;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_photo);
//获取各个控件对象
previousBtn = (Button)findViewById(R.id.previous);
nextBtn = (Button)findViewById(R.id.next);
picture = (ImageView)findViewById(R.id.picture);
//获取cursor
String[] columns = {Media.DATA,Media._ID,Media.TITLE,Media.DISPLAY_NAME};
cursor = managedQuery(Media.EXTERNAL_CONTENT_URI, columns, null, null, null);
//通过cursor获取各个列的索引
fileColumn = cursor.getColumnIndexOrThrow(Media.DATA);
//ImageView触屏事件
picture.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
float downX = 0;
float downY = 0;
float upX = 0;
float upY = 0;
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = event.getX();
downY = event.getY();
pictureBmp = Bitmap.createBitmap(getBitmap(imageFilePath), (int)downX, (int)downY, 20, 20);
canvas.drawBitmap(pictureBmp, event.getX(),event.getY() , paint);
picture.setImageBitmap(cloth);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
upX = event.getX();
upY = event.getY();
break;
default:
break;
}
return true;
}
});