我在android studio中创建了一个正方形,我的代码在下面。我不知道如何集中它。此刻,我从20位的x位置和20位的位置开始。如何使它居中,我是否只需要继续使用坐标,或者是否有办法完全按照坐标进行操作?
package com.example.cms0369.somethingelse;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class Draw extends View {
Paint paint = new Paint();
//float startX;
//float startY;
//float stopX;
//float stopY;
public Draw(Context context){
super(context);
paint.setColor(Color.BLACK);
}
@Override
public void onDraw(Canvas canvas){
canvas.drawLine(20, 20, 200, 20, paint);
canvas.drawLine(20, 20, 20, 200, paint);
canvas.drawLine(20, 200, 200, 200, paint);
canvas.drawLine(200, 200, 200, 20, paint);
}
}
答案 0 :(得分:1)
您可以尝试这样的事情:
int rectSide = ...;
@Override
public void onDraw(Canvas canvas){
int width = canvas.getWidth();
int height = canvas.getHeight();
canvas.drawRect(width/2f - rectSide/2f,
height/2f - rectSide/2f,
width/2f + rectSide/2f,
height/2f + rectSide/2f, paint);
}