Java on android studio, why I cant see the Rectangle i drew in canvas?

Hi guys I recently started developing an android game, but i have encountered an issue with drawRectangle.

public void draw(Canvas canvas) {
    super.draw(canvas);

    canvas.drawColor(Color.BLACK);
    canvas.drawRect(new Rect(100,100,100,100), new Paint(Color.WHITE));

}

this Doesnt seem to work, but i have already drew on screen using another class with a draw method using the same logic but im curious why this doesnt work

private Paint myPaint = new Paint();

@Override
public void draw(Canvas canvas) {
    super.draw(canvas);
    canvas.drawColor(Color.BLACK);
    myPaint.setColor(Color.WHITE);
    canvas.drawRect(new Rect(100,100,100,100), myPaint);


}

this doesnt work either

Upvotes: 0

Views: 162

Answers (3)

This worked

@Override
public void draw(Canvas canvas) {
    super.draw(canvas);

    canvas.drawColor(Color.BLACK);
    myPaint.setColor(Color.WHITE);
    canvas.drawRect(testRect, myPaint);

}

Where private Rect testRect = new Rect(0,0,100,100}

private Paint myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

Upvotes: 0

Nishant Chauhan
Nishant Chauhan

Reputation: 744

There are three issues in your implementation:-

  • Paint object doesn't take color in constructor, it takes a flag. So you could have done something like Paint p = new Paint(Paint.ANTI_ALIAS_FLAG) and then set the color as p.setColor(Color.WHITE).
  • The Rect object should be something like new Rect(0,0,100,100). In your case [new Rect(100,100,100,100)] the rectangle will be drawn as a rectangle with 0 width, 0 height and its upper left coordinate will be (100,100) and its bottom right coordinate will be (100,100).
  • NEVER create objects in onDraw.

Upvotes: 1

Gabe Sechan
Gabe Sechan

Reputation: 93561

Paint's constructor doesn't take a color. It takes integer flags. So you just made a really weird paint object with every flag set, but you didn't set the color.

See: https://developer.android.com/reference/android/graphics/Paint.html#Paint(int)

Upvotes: 0

Related Questions