如何在卡瓦斯上绘制许多位图



我想在画布上绘制许多位图,但 android 显示:"应用程序可能在其主线程上做了太多工作"并且应用程序无法运行。[ cloud_number超过 50 ]

这是我的代码:

fun draw_beautiful(canvas: Canvas){
val mPaint: Paint = Paint()
mPaint.style = Paint.Style.FILL
mPaint.isAntiAlias = true
mPaint.color= Color.BLACK
var vt = 0; var x1 =0f; var y1 =0f;var style =0;
for (i in 1..cloud_number){
vt = i*4-3
style = mt_cloud[vt]
x1  = mt_cloud[vt+2].toFloat()
y1 = mt_cloud[vt+3].toFloat()

var ob= canvas_cloud1
if (style==0) ob= canvas_cloud1
else if (style==1) ob= canvas_cloud2
else if (style==2) ob= canvas_cloud3
canvas.drawBitmap(ob, x1,y1 , mPaint)
}
}

从您发布的代码来看,函数中的大多数操作都不涉及视图。与视图交互的唯一部分是画布绘制操作。因此,正如注释中指出的那样,您应该在工作线程中运行所有计算,然后使用可运行对象调用 runOnUIThread 以在画布上执行最终绘图。runOnUIThread 调用将防止 android 抛出当您从未绑定到 UI 的工作线程修改视图时发生的错误。

您在这里的选项显然是 AsyncTask 和线程类。在下面的例子中,我使用的是AyncTask。

void draw_beautiful(Canvas canvas) {
MyDrawingWorkerTask myDrawingWorkerTask = new MyDrawingWorkerTask(this);
myDrawingWorkerTask.execute(canvas);
}

/**
* A class for doing a lot of the work in a background
*/
private static class MyDrawingWorkerTask extends AsyncTask<Canvas, Void, Void> {
private final Activity activity;
public MyDrawingWorkerTask(Activity activity) {// add more parameters to use to set other variables like cloud_number, etc
this.activity = activity;
}
// This is where the work is being done
@Override
protected Void doInBackground(Canvas... canvases) {
final Canvas canvas = canvases[0];
final Paint mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL);
mPaint.setAntiAlias(true);
mPaint.setColor(Color.BLACK);
int vt = 0;
float x1 = 0f;
float y1 = 0f;
int style = 0;
for (int i = 0; i < cloud_number; i++) {
vt = i * 4 - 3;
style = mt_cloud[vt];
x1 = mt_cloud[vt + 2].toFloat();
y1 = mt_cloud[vt + 3].toFloat();

Bitmap ob = canvas_cloud1;
if (style == 0) ob = canvas_cloud1;
else if (style == 1) ob = canvas_cloud2;
else if (style == 2) ob = canvas_cloud3;
Bitmap finalOb = ob;
float finalX = x1;
float finalY = y1;
// note that this is what interacts with the view
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
canvas.drawBitmap(finalOb, finalX, finalY, mPaint);
}
});
}
return null;
}
}

最新更新