【发布时间】:2016-02-07 06:30:04
【问题描述】:
我正在尝试将 OnTouchListener 设置为 ImageView,在该 ImageView 上进行大量自定义绘图。问题:我的 X 值已关闭,并且我经常将触摸记录到左侧太远。虽然 Y 值没问题,但我的算法的问题在哪里?
我使用的画布是 400 像素宽和 300 像素高。我没有对 ImageView 应用任何特殊的缩放,我只是依靠标准的 ImageView 行为,它会自行缩放以适应屏幕。小绿点应该出现在用户触摸屏幕的位置,但它们在我的 Nexus 5 上离左侧太远了。我的数学对于 Y 值是正确的,但在 X 值上是错误的,这是怎么回事?我要求 x 比例和 y 比例,所以即使 ImageView 正在改变纵横比,我也应该考虑到这一点,对吧?
public class FullscreenActivity extends AppCompatActivity {
private ImageView drawingImageView;
private Canvas canvas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int mUIFlag = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
getWindow().getDecorView().setSystemUiVisibility(mUIFlag);
setContentView(R.layout.activity_fullscreen);
drawingImageView = (ImageView) this.findViewById(R.id.game_map_fixed_id);
Bitmap bitmap = Bitmap.createBitmap(Map.width, Map.height, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
drawingImageView.setImageBitmap(bitmap);
drawingImageView.setOnTouchListener(mapOnTouchListener);
}
View.OnTouchListener mapOnTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
float[] bounds = new float[6];
bounds = getBitmapPositionInsideImageView(drawingImageView);
float x = event.getX() / bounds[4] - bounds[0];
float y = event.getY() / bounds[5] - bounds[1];
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setColor(Color.GREEN);
canvas.drawCircle(x, y, 1, paint);
return false;
}
};
public static float[] getBitmapPositionInsideImageView(ImageView imageView) {
float[] rect = new float[6];
if (imageView == null || imageView.getDrawable() == null)
return rect;
// Get image dimensions
// Get image matrix values and place them in an array
float[] f = new float[9];
imageView.getImageMatrix().getValues(f);
// Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
final float scaleX = f[Matrix.MSCALE_X];
final float scaleY = f[Matrix.MSCALE_Y];
rect[4] = scaleX;
rect[5] = scaleY;
// Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
final Drawable d = imageView.getDrawable();
final int origW = d.getIntrinsicWidth();
final int origH = d.getIntrinsicHeight();
// Calculate the actual dimensions
final int actW = Math.round(origW * scaleX);
final int actH = Math.round(origH * scaleY);
rect[2] = actW;
rect[3] = actH;
// Get image position
// We assume that the image is centered into ImageView
int imgViewW = imageView.getWidth();
int imgViewH = imageView.getHeight();
float left = (imgViewW - actW)/2;
float top = (imgViewH - actH)/2;
rect[0] = left;
rect[1] = top;
return rect;
}
}
【问题讨论】:
标签: android canvas bitmap imageview