简体   繁体   中英

How to Draw a point on over a bitmap image drawn on a canvas by specifying the x and y co-ordinate in android?

I have drawn a bitmap image over a canvas.

Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.sq);
        canvas.drawColor(color.black);  
        Rect dstRectForRender = new Rect(0,0,320,450);               
        canvas.drawBitmap(image, null,dstRectForRender,null);   

The image gets displayed based on my screnn on a cnavs. On my touch input, I need to pass the x and y co-ordinate position of the image and fill that pixel with a color to show that the image is painted on a drag event. How can I pass the x and y coo-ordinate parameters? Which functions should I use to plot the pixels on the image? I appreciate your help and sweet time.

I'm not sure if this is the best way to do this, but it would be much easier to do this if you defined your own subclass of ImageView and name it something like DrawableImageView . You'd have to make sure you implement all the basic constructors from ImageView , then override the onTouchEvent method. From that event you can get the touch coordinates and store them in an ArrayList<Point> and use that ArrayList by overriding the onDraw method and "painting" the image.

public class DrawableImageView extends ImageView {

ArrayList<Point> list = new ArrayList<Point>();    

//constructors..

@Override
public boolean onTouchEvent (MotionEvent event) {
    float x = event.getX();
    float y = event.getY();
    list.add(new Point(x,y));
    invalidate();
}

This is just a very brief overview of how to start your class, and may not be the most accurate way of doing things (depending on your specific code). Now, instead of using <ImageView> tags in your xml (or, loading an ImageView programatically), you refer to your subclass like so:

<your.package.name.DrawableImageView
/>

Edit

In response to your comment, there is no predetermined way to draw over an image. You must implement this yourself, which is why I recommended storing Points in an ArrayList. I'm not really sure what you're trying to achieve here, but to draw (for example) black dots over an image you have to override onDraw :

public void onDraw(Canvas c) {
    super.onDraw(c);
    for(Point p : list) {

        //Draw black point at x and y.. I'm posting from my cell so I can't go into much detail
   }
}

Also, to force a View to redraw itself you need to use the invalidate() method in your onTouchEvent() (which I've added above).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM