首页 > 解决方案 > 在画布上绘制只需启动 Activity

问题描述

我正在尝试从自定义视图在画布上绘制测试线。它在我调用我的方法时起作用drawBeats(),例如通过按下按钮,但我想在应用程序启动时drawBeats()通过MainActivity's执行。onCreate()以下是我的自定义视图的相关行:

    public MetronomeBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        ...
        width = this.getWidth();
        height = this.getHeight();

        onMeasure(width, height);
        onSizeChanged(width, height,100, 100);
        onDraw(drawCanvas);
    }

    public void drawBeats() {
        drawPaint.setStrokeWidth(40);
        drawPaint.setColor(0xFFAAA9A9);
        drawCanvas.drawLine(0, 0, 0, 30, drawPaint);
        invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int desiredWidth = 100;
        int desiredHeight = 100;

        int widthMode = MeasureSpec.AT_MOST;
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.AT_MOST;
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        //Measure Width
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {
            //MATCH_PARENT
            width = Math.max(desiredWidth, widthSize);
        } else {
            width = desiredWidth;
        }

        //Measure Height
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            //MATCH_PARENT
            height = Math.max(desiredHeight, heightSize);
        } else {
            height = desiredHeight;
        }

        //MUST CALL THIS
        setMeasuredDimension(width, height);
    }

    @Override
   protected void onSizeChanged(int w, int h, int oldw, int oldh){
        super.onSizeChanged(w, h, oldw, oldh);
        canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        drawCanvas = new Canvas(canvasBitmap);
    }

    @Override
    protected void onDraw(Canvas canvas){
        canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
    }
}

这就是我打电话drawBeats()的方式MainActivity

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
           ...
            mBar = findViewById(R.id.mBar);
            ...
            mBar.drawBeats();
        }

我需要强制onMeasure()onSizeChanged()并且onDraw()为了在非空的画布上绘制。我也尝试过drawBeats()在线程内部。画布的背景从一开始就可见。我只想在打开应用程序时画一些东西,但必须在这个特定的画布上。

标签: javaandroid

解决方案


我认为这个代码实验室会有所帮助。您不能在构造函数中调用视图生命周期事件。

onMeasure(width, height); onSizeChanged(width, height,100, 100); onDraw(drawCanvas);

教程也将很有用。


推荐阅读