5

我在这里阅读了有关此主题的不同问题,但我仍然找不到答案。出于任何原因,请随时关闭此问题。

我有一个简单的Circle类扩展View.

这个类的代码是:

public class ProgressCircle extends View {
    Paint mCirclePaint;
    float extRadius;
    float viewWidth, viewHeight;
    float centerX, centerY;

    public ProgressCircle(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
        init();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        float xpad = (float) getPaddingLeft() + getPaddingRight();
        float ypad = (float) getPaddingTop() + getPaddingBottom();
        float ww = (float)w - xpad; float hh = (float)h - ypad;
        extRadius = Math.min(ww, hh) / 2;

        viewWidth = this.getWidth();
        viewHeight = this.getHeight();
        centerX = viewWidth / 2; centerY = viewHeight / 2;

        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(centerX, centerY, extRadius, mCirclePaint);
        canvas.drawText("ciao", 0, 0, mCirclePaint);    
    }

    private void init() {
        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setColor(0x666666);
        mCirclePaint.setStyle(Paint.Style.FILL_AND_STROKE);
    }

我确认这个类中的每个方法都是在创建主要活动时调用的(通过使用 some Log.d()s)。我<com.mypackage.Circle>在我的主要活动中添加了一个元素,LinearLayout然后我添加了一个示例测试按钮。

我所取得的成果是显示按钮,而 myCircle没有显示,但按钮(在LinearLayout之后出现Circle)不是布局的第一个元素:这让我认为确实发生了某些事情,但没有绘制任何内容。

4

3 回答 3

4

这只是一个愚蠢的问题:颜色mCirclePaint.setColor(0x666666)是无效的。它与文件夹mCirclePaint.setColor(Color.RED)中定义的任何其他颜色一起使用。res

如果您需要指定颜色值,则必须包含透明度字节(否则它不是您指定的 32 位整数,而是 24 位)。所以 0x666666 是无效的,但是 0xff666666 是一个有效的颜色并且会绘制。

于 2013-02-24T13:38:45.607 回答
0

After reading the documentation(http://developer.android.com/guide/topics/graphics/2d-graphics.html):

The Android framework will only call onDraw() as necessary. Each time that your application is prepared to be drawn, you must request your View be invalidated by calling invalidate(). This indicates that you'd like your View to be drawn and Android will then call your onDraw() method (though is not guaranteed that the callback will be instantaneous).

Also another thing worth checking is the dimensions you're drawing insure nothing is invalid like a height of 0 etc..

于 2013-02-22T14:11:13.280 回答
0

我注意到您没有覆盖View.onMeasure()

因为您没有覆盖此方法,所以onsizeChanged()可能会传递大小 0。您可以通过在onSizechanged()方法中放置断点或打印到 Logcat 来检查这一点。

于 2013-02-22T14:24:18.777 回答