在安卓中将画布转换为位图图像

53

我正在尝试在画布上开发一个应用程序,我在画布上绘制了一个位图。绘制完成后,我正在尝试将其转换为位图图像。

是否有人能给我建议?


你已经获得了一个位图对象,还是想将此画布保存为位图文件? - hxc
4个回答

76

建议取决于你想要做什么。

如果您担心控件绘制所花费的时间太长,并且想要绘制到位图中,以便可以通过位图进行blit而不是通过画布重新绘制,则需要双重猜测平台-控件自动缓存其绘图到临时位图中,甚至可以使用getDrawingCache()从控件中获取它们。

如果您想使用画布绘制位图,通常的步骤是:

  1. 使用Bitmap.createBitmap()创建正确大小的位图
  2. 使用Canvas(Bitmap)构造函数创建指向该位图的画布实例
  3. 在画布上绘制
  4. 使用位图

27

你可以创建一个新的Bitmap,例如:

Bitmap myBitmap = new Bitmap((int)Width, (int)Height, Config.RGB_565)

其中widthheight与你的画布大小相同。

接下来,使用canvas.setBitmap(myBitmap)而不是drawBitmap()

在调用setBitmap之后,所有绘制在画布上的内容实际上都是在你的myBitmap上进行的,就像我所举的例子中那样。

编辑:

你不能直接创建一个位图,例如:

Bitmap myBitmap = new Bitmap( (int)Width, (int)Height, Config.RGB_565 );

您必须使用以下内容:

Bitmap myBitmap = Bitmap.createBitmap( (int)Width, (int)Height, Config.RGB_565 );

太好了。终于从你的回答中理解了它是如何工作的。那么,我可以将我的绘图的某些部分转换为位图,并重新绘制已经存储在某个数组中的准备好的位图,以实现你所描述的绘制优化吗?这将是一个好消息。 - Serg Burlaka

2

其他例子:

public Bitmap getBitmapNews(int item , boolean selected, int numbernews){                   
        Bitmap bitmap;

        if(selected)
            bitmap=mBitmapDown[item].copy(Config.ARGB_8888, true);
        else 
            bitmap=mBitmapUp[item].copy(Config.ARGB_8888, true);

        Canvas canvas = new Canvas(bitmap);

        if(numbernews<10){
        canvas.drawBitmap(mNotiNews[numbernews],0,0,null);
        }else{
            canvas.drawBitmap(mNotiNews[0],0,0,null);
        }

 return bitmap; 
}

1

以下是将画布转换为位图并存储到相册或特定文件夹的步骤。

注意:确保您已授予WRITE_EXTERNAL_STORAGE权限。

activity_main.xml

            <LinearLayout
                android:id="@+id/linearLayout"
                android:orientation="horizontal"
                android:layout_margin="10dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <DrawingView
                    android:id="@+id/drawingView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

            </LinearLayout>

MainActivity.java

  1. Create reference of parent layout

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
    
  2. To store it into gallery

    final String imagename = UUID.randomUUID().toString() + ".png";
    MediaStore.Images.Media.insertImage(getContentResolver(), linearLayout .getDrawingCache(), imagename, "drawing");
    
  3. To convert into bitmap

    linearLayout.setDrawingCacheEnabled(true);
    linearLayout.buildDrawingCache();
    Bitmap bitmap = Bitmap.createBitmap(linearLayout.getDrawingCache());
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接