android - 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);
}
}
解决方案
您不能调用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);
}
推荐阅读
- sql - SQL 按字段分组,每个分组只返回一个连接行
- python - CuPy random - 如何在同一内存中生成新的随机集?
- multithreading - 操作问题 qustions - 以上代码的线程、进程等:
- c# - 使用 itext7 添加文本
- azure - 用户第一次登录时是否可以更改 AD B2C 的布局更新密码页面
- c# - 创建一个通用列表
- javascript - 如何获取对象的总数组
- node.js - 如何使用 nodejs 从图像中查找自定义徽标
- c++ - jpegenc - 使用 VideoWrite() OpenCV 函数编码 + 存储
- angular - Angular 表单验证如何将嵌套表单控件添加到 FormData