首页 > 解决方案 > onDraw 方法不绘图

问题描述

我正在处理我的 ondraw 方法无法正常工作的应用程序。我检查了类似的问题,但我没有得到问题是什么。此代码绘制了一个正方形,但大小不正确。它是如此之小。我还为单元格编写了代码,但它们甚至都不起作用。我没有得到问题出在哪里。

我的班级代码:

public SudokuBoard(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    setWillNotDraw(false);
    setWillNotCacheDrawing(false);

    TypedArray a = context.getTheme().obtainStyledAttributes(attrs,R.styleable.SudokuBoard,0,0);

    try{
        boardColor = a.getInteger(R.styleable.SudokuBoard_boardColor,0);
    }
    finally {
        a.recycle();
    }
}


@Override
protected void onMeasure(int width, int height){
    super.onMeasure(getWidth(),getHeight());

    int dimension = Math.min(this.getMeasuredWidth(),this.getMeasuredHeight());
    cellSize = dimension/9;
    setMeasuredDimension(dimension,dimension);
}
@Override
protected void onDraw(Canvas canvas){

    boardColorPaint.setStyle(Paint.Style.STROKE);
    boardColorPaint.setStrokeWidth(16);
    boardColorPaint.setColor(boardColor);
    boardColorPaint.setAntiAlias(true);
    canvas.drawRect(0,0,getWidth(),getHeight(),boardColorPaint);
    drawBoard(canvas);

}
private void drawThinLine(){
    boardColorPaint.setStyle(Paint.Style.STROKE);
    boardColorPaint.setStrokeWidth(10);
    boardColorPaint.setColor(boardColor);

}
private void drawThickLine(){
    boardColorPaint.setStyle(Paint.Style.STROKE);
    boardColorPaint.setStrokeWidth(4);
    boardColorPaint.setColor(boardColor);
}

private void drawBoard(Canvas canvas){
    for(int c = 0;c<10;c++){
        if(c%3==0){
            drawThickLine();
        }
        else{
            drawThinLine();
        }
        canvas.drawLine(cellSize*c,0,cellSize*c,getWidth(),boardColorPaint);

    }
    for(int r = 0;r<10;r++){
        if(r%3==0){
            drawThickLine();
        }
        else{
            drawThinLine();
        }
        canvas.drawLine(0,cellSize*r,getWidth(),cellSize*r,boardColorPaint);

    }

}

标签: android

解决方案


您不能调用getMeasuredWidth()getMeasuredHeight()从内部调用onMeasure(),这些值在setMeasuredDimension()调用之前不会确定。

你也不应该打电话super.onMeasure(),你的工作onMeasure()是计算尺寸和打电话setMeasuredDimension()

假设您的 SodukoBoard 设置为layout_width="match_parent"layout_height="match_parent",此代码应使用两个维度中较小的一个将您的 SodukoBoard 宽度设置为正方形:

void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
{
 int dimension = Math.min(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
 setMeasuredDimension (dimension, dimension);
}

推荐阅读