java - 在画布上绘制只需启动 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()
在线程内部。画布的背景从一开始就可见。我只想在打开应用程序时画一些东西,但必须在这个特定的画布上。
解决方案
推荐阅读
- pandas - 如何从数据框创建组?
- roles - 无法使用 compute.backendServices.addSignedUrlKey 权限创建自定义角色
- escaping - Blazor SessionStorage - Itens 以转义字符返回
- docker - Docker(在 Azure 应用服务中)空间不足
- oracle-jet - 内容服务器请求失败
- dnf - 如何创建可以在离线 Fedora 机器上与 dnf 一起使用的离线更新存储库?
- sql-server - SSRS 中的列根据 SSRS 中的参数值显示值
- datetime - 使用 DotLiquid 显示 DateTime meridiem 不起作用
- antlr - 在 ANTLR Lexer 规则中包含某些擒纵符号
- java - 空手道输入匹配