过去2个小时我一直在努力解决这个问题,而我却无法得到答案。我想要我的relativelayout的中心,因为我想用画布在那里画一个圆圈。我已经尝试过了:
这是我的代码:
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
Bitmap bg = Bitmap.createBitmap(480, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bg);
rel = (RelativeLayout) findViewById(R.id.relPaint);
//canvas.drawPaint(paint);
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(centreX, centreY, 50, paint);
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
rel.setBackgroundDrawable(new BitmapDrawable(getResources(), bg));
} else {
rel.setBackground(new BitmapDrawable(getResources(), bg));
}
}
@Override
protected void onStart() {
centreX = rel.getX() + rel.getWidth() / 2;
centreY = rel.getY() + rel.getHeight() / 2;
super.onStart();
}
变量rel,centreX和centreY在全球范围内声明。感谢。
答案 0 :(得分:1)
看看Activity Lifecycle。在onCreate()
之前调用onStart()
。您首先绘制圆,然后计算布局的中心。在OnCreate()
。
并像这样计算centreX
和centreY
。
rel.post(new Runnable() {
@Override
public void run() {
centreX = rel.getWidth() / 2;
centreY = rel.getHeight() / 2;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
Bitmap bg = Bitmap.createBitmap(480, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bg);
rel = (RelativeLayout) findViewById(R.id.relPaint);
//canvas.drawPaint(paint);
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(centreX, centreY, 50, paint);
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
rel.setBackgroundDrawable(new BitmapDrawable(getResources(), bg));
} else {
rel.setBackground(new BitmapDrawable(getResources(), bg));
}
}
});