53

我正在尝试在画布上开发应用程序,我正在画布上绘制位图。绘制后,我正在尝试转换为位图图像。

谁能给我一个建议?

4

4 回答 4

74

建议取决于您要做什么。

如果您担心您的控件需要很长时间才能绘制,并且您想绘制位图以便您可以位图而不是通过画布重新绘制,那么您不想怀疑平台- 控件自动将其绘图缓存到临时位图,这些甚至可以使用从控件中获取getDrawingCache()

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

  1. 使用创建正确大小的位图Bitmap.createBitmap()
  2. Canvas(Bitmap)使用构造函数创建一个指向该位图的画布实例
  3. 绘制到画布
  4. 使用位图
于 2010-10-25T10:43:35.353 回答
26

所以你创建一个新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 );
于 2012-07-11T16:45:18.913 回答
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; 
}
于 2014-02-19T09:07:02.747 回答
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. 创建父布局的引用

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
    
  2. 将其存储到图库中

    final String imagename = UUID.randomUUID().toString() + ".png";
    MediaStore.Images.Media.insertImage(getContentResolver(), linearLayout .getDrawingCache(), imagename, "drawing");
    
  3. 转换成位图

    linearLayout.setDrawingCacheEnabled(true);
    linearLayout.buildDrawingCache();
    Bitmap bitmap = Bitmap.createBitmap(linearLayout.getDrawingCache());
    
于 2017-01-11T06:20:08.603 回答