我想在图像视图中显示的图像的特定坐标处绘制。我使用imageview的src属性将图像加载到视图中。此代码用于自定义imageview中以在图像上绘制:
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float scaleh =(float)canvas.getHeight()/(float)orginalheight();
float scalew = ((float)canvas.getWidth()/(float)orginalwidth());
canvas.drawRect(10*scaleh,9*scalew,20*scaleh,30*,scalewpaint);
}
此代码在错误的位置绘制矩形。有什么问题?
答案 0 :(得分:0)
您应该从ImageView
本身而不是Canvas
获取视图的尺寸,尤其是当不可靠的目标是在ImageView
内绘制图像时。
Canvas适合您作为实际的假装或界面 将绘制图形的表面 - 它可以保存您的所有图形 “画”电话。通过画布,您的绘图实际上是在执行 底层的Bitmap,放在窗口中。
首先,为了获得坐标,请为onTouchListener
实施ImageView
。这将为您提供X和Y坐标来绘制Canvas
。
imageView.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
xDown = event.getX();
yDown = event.getY();
break;
case MotionEvent.ACTION_MOVE:
xUp = event.getX();
uUp = event.getY();
canvas.drawLine(xDown, yDown, xUp, uUp, paint);
imageView.invalidate();
xDown = xUp;
yDown = uUp;
break;
case MotionEvent.ACTION_UP:
xUp = event.getX();
uUp = event.getY();
canvas.drawLine(xDown, yDown, xUp, uUp, paint);
imageView.invalidate();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}});
然后创建一个Canvas
以在ImageView上绘制。
//Create a new image bitmap and attach a brand new canvas to it
Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(tempBitmap);
paint = new Paint();
paint.setColor(YOUR_DESIRED_COLOR);
paint.setStrokeWidth(INT_VALUE);
matrix = new Matrix();
canvas.drawBitmap(bmp, matrix, paint);
//Attach the canvas to the ImageView
imageViewsetImageBitmap(tempBitmap);
如果您想简单地绘制矩形,也可以使用canvas.drawRect(left,top,right,bottom,paint);
。
希望它有所帮助。