Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current canvas?

I have DrawView. If I touch this view it draws small circles. I wont to draw circles but not to touch view - with help function "setPoints". What I do:

package com.samples;
import ...

public class DrawView extends View {
    ArrayList<Point> points = new ArrayList<Point>();

    Paint paint = new Paint();

    private int pSize = 5;
    private int pColor = Color.BLACK;

    public DrawView(Context context, AttributeSet attrs) {

        super(context, attrs);

        setFocusable(true);
        setFocusableInTouchMode(true);

        this.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.setOnTouchListener(this);
                    Point point = new Point();
                    point.x = event.getX();
                    point.y = event.getY();
                    points.add(point); 
                    invalidate();
                }
                return true;
            }
        });
        requestFocus();
    }

    @Override
    public void onDraw(Canvas canvas) { 
        for (Point point : points) {
            canvas.drawCircle(point.x, point.y, pSize, paint);
        }
    }

    public void setPoints(Float xP, Float yP)
    {
        Point point = new Point();
        point.x = xP;
        point.y = yP;
        points.add(point);
        postInvalidate();
    }
}

class Point {
    float x, y;

    @Override
    public String toString() {
        return x + ", " + y;
    }
}

Please tell me, how get canvas out setPoints function?

Update: Wow, it's really interesting problem. My DrawView contains in HorizontalScrollView. Because if I set in this DrawView right coordinates, no one knows where are drawable circles.

like image 924
Leo Avatar asked Feb 10 '12 19:02

Leo


3 Answers

You can't. The canvas is managed by the system and is passed to your onDraw(). I don't understand why you'd need it outside of there. Just redeclare setPoints like this

public void setPoints(Canvas canvas, Float xP, Float Yp)

You can keep a cache of the previous drawings (or store the previous points)

like image 176
Raffaele Avatar answered Oct 29 '22 23:10

Raffaele


Try declaring canvas2 as a public variable in the DrawView class.

like image 36
8oh8 Avatar answered Oct 29 '22 23:10

8oh8


You draw your circles in onDraw(). That's the way View is supposed to work (technically it's actually in the draw() method but we'll overlook that). In setPoints(), set the points of the circle in variables within the class scope, call invalidate(), then draw the circle like that in onDraw(). If you follow this method, you're following the class flow that the view was designed for.

like image 1
DeeV Avatar answered Oct 29 '22 23:10

DeeV