Chintan Rathod
Chintan Rathod

Reputation: 26034

Rectangle is not drawn at its original coordinates

I am facing problem while creating a CustomView which draw a Rectangle and can re-size by its corners.

Following is my code.

public class CustomView extends View {
    Canvas canvas;
    private Context mContext;
    private Rect rectObj;
    private Paint rectPaint;
    private Matrix transform;
    public CustomView(Context context) {
        super(context);
        mContext = context;
        initView();
    }
    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        initView();
    }
    public CustomView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void initView() {
        rectPaint = new Paint();
        rectPaint.setColor(Color.parseColor("#55000000"));

        setFocusable(true); // necessary for getting the touch events
        canvas = new Canvas();
        // setting the start point for the balls

        rectObj = new Rect(100, 100, 200, 200);

        // Create a matrix to do rotation
        transform = new Matrix();
    }

    @Override
    public void onDraw(Canvas canvas) {
        // This is an easy way to apply the same transformation (e.g.
        // rotation)
        // To the complete canvas.
        canvas.setMatrix(transform);

        // With the Canvas being rotated, we can simply draw
        // All our elements (Rect and Point)
        canvas.drawRect(rectObj, rectPaint);
    }
}

When I run this program, following output come.

enter image description here

As display in image, my "Rectangle"'s top-left are 100,100 but when I touch on "left-top corner of rectangle" on screen, x-y are 150,76 or something which are not match with original drawing.

I have to use canvas.setMatrix(transform) to rotate that rectangle in next phase.
Whats going wrong in this code?

Upvotes: 0

Views: 1350

Answers (1)

bogdan
bogdan

Reputation: 782

In the method onDraw(Canvas canvas) one thing you should do is calling the method super.onDraw(cavas), after that instead of doing 'canvas.setMatrix(transform);' you should do 'canvas.concat(transform);' because the canvas has an initial Matrix with some values saved. Also, if you just need to rotate or translate that rect, you can rotate and translate the canvas by doing canvas.rotate(degree) for example.

Upvotes: 1

Related Questions