幾點意見:
在确定圓的中心點和半徑時,您需要考慮配置設定給視圖的寬度和高度.
您應該考慮配置設定給視圖的填充,這樣就不會繪制該保留部分.
你應該避免在onDraw方法中配置設定對象,因為這會被調用很多.
為了允許在XML布局中指定視圖,您需要提供帶有Context和AttributeSet的構造函數. AttributeSet是将XML屬性傳遞給視圖的機制.
嘗試一下:
package com.tak3r07.montecarlopi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class CircleView extends View
{
private static final int DEFAULT_CIRCLE_COLOR = Color.RED;
private int circleColor = DEFAULT_CIRCLE_COLOR;
private Paint paint;
public CircleView(Context context)
{
super(context);
init(context,null);
}
public CircleView(Context context,AttributeSet attrs)
{
super(context,attrs);
init(context,attrs);
}
private void init(Context context,AttributeSet attrs)
{
paint = new Paint();
paint.setAntiAlias(true);
}
public void setCircleColor(int circleColor)
{
this.circleColor = circleColor;
invalidate();
}
public int getCircleColor()
{
return circleColor;
}
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int w = getWidth();
int h = getHeight();
int pl = getPaddingLeft();
int pr = getPaddingRight();
int pt = getPaddingTop();
int pb = getPaddingBottom();
int usableWidth = w - (pl + pr);
int usableHeight = h - (pt + pb);
int radius = Math.min(usableWidth,usableHeight) / 2;
int cx = pl + (usableWidth / 2);
int cy = pt + (usableHeight / 2);
paint.setColor(circleColor);
canvas.drawCircle(cx,cy,radius,paint);
}
}