如何使用Canvas - Android将图像从drawable绘制到imageview上

时间:2011-11-28 19:33:12

标签: android canvas imageview drawable

我的活动中有ImageView。我想要做的是能够绘制用户用可绘制文件夹中的图像触摸Imageview的位置。我已经读过最好的方法是使用Canvas,但我不确定将onDraw方法与onTouchListener集成的位置和方式。这就是我到目前为止所做的:

public class Main extends Activity
{
   @Override
   public void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      final TextView textView = (TextView)findViewById(R.id.textView);
      final ImageView image = (ImageView) findViewById(R.id.imageView2);

      //Bitmap
      Bitmap viewBitmap = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888);
      Canvas canvas = new Canvas(viewBitmap);
      image.draw(canvas);

      image.setOnTouchListener(new View.OnTouchListener()
      {
         @Override
         public boolean onTouch(View v, MotionEvent event)
         {
            textView.setText("Touch coordinates : " + String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
            return false;
         }
      });
   }
}

所以我想做的是当用户触摸ImageView时,图像将被准确地绘制在他触摸的位置。

1 个答案:

答案 0 :(得分:2)

您希望子类化ImageView以覆盖其onDraw()方法。通过这样做,您还可以在onTouchEvent()中进行自定义触摸处理,而不是附加侦听器。这不是一个完整的例子,但类似于以下内容:

public class CustomImageView extends ImageView {

    private ArrayList<Point) mTouches;
    private Bitmap mMarker;

    //Java constructor
    public CustomImageView(Context context) {
        super(context);
        init();
    }

    //XML constructor
    public CustomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mTouches = new ArrayList<Point>();
        mMarker = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_marker_image);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //Capture a reference to each touch for drawing
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            mTouches.add( new Point(event.getX(), event.getY()) );
            return true;
        }

        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas c) {
        //Let the image be drawn first
        super.onDraw(c);

        //Draw your custom points here
        Paint paint = new Paint();            
        for(Point p : mTouches) {
            c.drawBitmap(mMarker, p.x, p.y, paint);
        }
    }

}

HTH!