Reputation: 87
please see the following code. I want draw a rectangle in center of the screen.But it draws a rectangle in the left corner.
protected void onDraw(Canvas canvas) {
paint.setColor(Color.GREEN);
canvas.drawRect(getLeft()/2,getTop()/2,getRight()/2,getBottom()/2,paint);
super.onDraw(canvas);
}
Upvotes: 6
Views: 12889
Reputation: 81
var rectWidth = 200f
var rectHeight = 300f
val left = (width-rectWidth)/2
val top = (height-rectHeight)/2
val right = left+rectWidth
val bottom = top+rectHeight
canvas.drawRect(left, top, right, bottom, paint)
Upvotes: 0
Reputation: 19
Tested answer:
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
val canvasCenter = PointF(width/2f,height/2f)
val rectW = 300f
val rectH = 300f
val rect = RectF(canvasCenter.x - rectW,canvasCenter.y -rectH,
canvasCenter.x + rectW,canvasCenter.y + rectH)
canvas?.drawRect(rect,mPaintDest)
}
Upvotes: 1
Reputation: 1721
Find the center of the screen
x = width / 2.0
y = height / 2.0
Calculate the top left corner of your rect
topX = x - (rectWidth / 2.0)
topY = y - (rectHeight / 2.0)
Upvotes: 4
Reputation: 717
Something like that?
protected void onDraw(Canvas canvas) {
int canvasW = getWidth();
int canvasH = getHeight();
Point centerOfCanvas = new Point(canvasW / 2, canvasH / 2);
int rectW = 100;
int rectH = 100;
int left = centerOfCanvas.x - (rectW / 2);
int top = centerOfCanvas.y - (rectH / 2);
int right = centerOfCanvas.x + (rectW / 2);
int bottom = centerOfCanvas.y + (rectH / 2);
Rect rect = new Rect(left, top, right, bottom);
canvas.drawRect(rect, new Paint());
}
Upvotes: 16
Reputation: 7277
Try this
protected void onDraw(Canvas canvas) {
paint.setColor(Color.GREEN);
canvas.drawRect(
getLeft()+(getRight()-getLeft())/3,
getTop()+(getBottom()-getTop())/3,
getRight()-(getRight()-getLeft())/3,
getBottom()-(getBottom()-getTop())/3,paint);
super.onDraw(canvas);
}
Upvotes: 7