我一直在网上搜索如何将画布上的内容转换成位图。我尝试了多种方法,比如将绘制缓存保存到位图中,但最终结果是背景位图会闪烁一下,然后变成黑屏。测试图像显示在背景上,但不会被下一次调用 OnDraw
的背景覆盖。
MainThreading{
...
if(notuptodate == true){
//call readyBackground to create the background bitmap
this.mainPanel.readyBackground(canvas);
//post the canvas
surfaceHolder.unlockCanvasAndPost(canvas);
//clean the Canvas
canvas = null;
//ready new Canvas
canvas = this.surfaceHolder.lockCanvas();//lock the canvas to enable editing
}//if not true
if (MainThreading.notuptodate == false){
mainPanel.onDraw(canvas);
}//if false
...
}//mainthreading
//this method is run first to create the Bitmap that on draw will use
public void readyBackGround(Canvas canvas){
if (MainThreading.notuptodate){
//method used to draw multiple Bitmaps onto the canvas
renderBackground(canvas);
//private Bitmap, this is the supposed proper size of the bitmap
backgroundBitmap=Bitmap.createBitmap(240, 320, Config.ARGB_8888);
//set the canvas to turn whats on its self onto the bitmap.
canvas.setBitmap(backgroundBitmap);
//set boolean flag to false so renderBackground won't be called
//untill it needs to be updated again
MainThreading.notUpToDate = false;
}
//this method is called when notUpToDate = true
@Override
protected void onDraw(Canvas canvas){
if (this.threado.getBackground() != null){
canvas.drawBitmap(backgroundBitmap, 0, 0, null);
}
//this if statement is never activated
if (this.threado.getBackground() == null){
Log.d("background nonexistant", "Importante!");
}
//draw test object onto background
test.DrawObject(canvas);
//when MainThreading.notUpToDate = true isn't commented out, the
//screen consistantly shows the background, but the test object isn't
//drawn
//MainThreading.notUpToDate = true;
}
// 创建位图对象 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); // 创建画布对象并绑定到位图上 Canvas canvas = new Canvas(bm); // 在画布上绘制需要转换的内容 view.draw(canvas); // 将位图压缩到输出流上(这里使用了ByteArrayOutputStream作为输出流) ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] byteArray = baos.toByteArray();
以上代码将视图view绘制在指定宽度和高度的位图上,并将其压缩为PNG格式的字节数组。可以根据需要改变压缩格式和质量值。 - AlexAndro