以编程方式将视图放在活动中

时间:2014-12-18 10:47:51

标签: android android-canvas paint

我正在尝试绘制一个表示活动中电池寿命的圆周。

我的父布局是相对布局。

这是绘制视图的内部类:

public class DrawView extends View {
    Paint mPaint = new Paint();

    public DrawView(Context context) {
        super(context);
    }

    @Override
    public void onDraw(Canvas canvas) {
        Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG |
                Paint.DITHER_FLAG |
                Paint.ANTI_ALIAS_FLAG);
        mPaint.setDither(true);
        mPaint.setColor(Color.GRAY);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(1);

        int size = 200;
        int radius = 190;
        int delta = size - radius;
        int arcSize = (size - (delta / 2)) * 2;
        int percent = 42;

        //Thin circle
        canvas.drawCircle(size, size, radius, mPaint);

        //Arc
        mPaint.setColor(getResources().getColor(R.color.eCarBlue));
        mPaint.setStrokeWidth(15);
        RectF box = new RectF(delta,delta,arcSize,arcSize);
        float sweep = 360 * percent * 0.01f;
        canvas.drawArc(box, 0, sweep, false, mPaint);
    }

}

在onCreate()中,我以这种方式启动视图:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ...

    ViewGroup myLayout = (ViewGroup) findViewById(R.id.mainlayout);
    drawing = new DrawView(this);
    myLayout.addView(drawing);
}

但我需要在布局中找到这个视图,特别是在它的中心。为此,我以这种方式修改了onCreate()的代码:

ViewGroup myLayout = (ViewGroup) findViewById(R.id.mainlayout);
drawing = new DrawView(this);
RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
drawing.setLayoutParams(layoutParams);
myLayout.addView(drawing);

但它对视图没有影响。那么为视图定义参数的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您正在DrawView添加LayoutParams.WRAP_CONTENT,这意味着系统需要询问视图的宽度和高度。你应该为此实现onMeasure()。但是我从未这样做过,所以不了解细节。

另一种方法是只使用LayoutParams.MATCH_PARENT并以onDraw()为中心绘制您的内容。在这种情况下,您需要知道画布的宽度和高度,以便计算绘制调用的坐标。在getWidth()中拨打onDraw()并未提供预期的结果。您需要覆盖onSizeChanged()并记录新的宽度和高度,如下所示:

private int canvasWidth;
private int canvasHeight;

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    canvasWidth = w;
    canvasHeight = h;
}

然后在onDraw()中,您可以使用canvasWidthcanvasHeight,因为onSizeChanged()已经发生。