我想检测View
内触摸的对象。
这是我的View
public class TouchView extends View {
private Matrix translate;
private Bitmap image, background;
private float scaleFactor = 1.0f;
private ScaleGestureDetector scaleGestureDetector;
private GestureDetector simpleOnGestureListener;
public TouchView(Context context) {
super(context);
translate = new Matrix();
image = BitmapFactory.decodeResource(context.getResources(), R.drawable.photo);
//background = decodeFile(R.drawable.background);
scaleGestureDetector = new ScaleGestureDetector(context, new ScaleListener());
simpleOnGestureListener = new GestureDetector(context, new MyGestureListener(this));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.scale(scaleFactor, scaleFactor);
canvas.drawBitmap(background, translate, null);
canvas.drawBitmap(image, translate, null);
Matrix m = canvas.getMatrix();
canvas.restore();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
scaleGestureDetector.onTouchEvent(event);
simpleOnGestureListener.onTouchEvent(event);
invalidate();
return true;
}
private class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final String DEBUG_TAG = "Gestures";
TouchView view;
public MyGestureListener(TouchView view) {
this.view = view;
}
@Override
public boolean onDown(MotionEvent event) {
return true;
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
view.onMove(-distanceX, -distanceY);
invalidate();
return true;
}
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(0.6f, Math.min(scaleFactor, 2.0f));
invalidate();
return true;
}
}
public Bitmap decodeFile(int resId) {
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getContext().getResources(), resId, o);
//find the correct scale value. it should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
//decode wit inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeResource(getContext().getResources(), resId, o2);
} catch (Exception e) {
e.getStackTrace();
}
return null;
}
public void onMove(float dx, float dy) {
translate.postTranslate(dx, dy);
invalidate();
}
}
有没有办法检测照片是否被点击或背景? 我想让你们两个都可以移动,但如果我点击照片我想手动移动它。不是整个观点。
亲切的问候!
答案 0 :(得分:1)
我并不完全明白你想要什么。但是,正如我从您的代码中发现的那样,您希望在视图中显示两个图像(背景和前景)。 您需要检查触摸位置(使用getX()和getY())。如果前景图像矩形包含该点,则触摸您的对象,否则触摸背景。