我正在尝试在画布上开发一个应用程序,我在画布上绘制了一个位图。绘制完成后,我正在尝试将其转换为位图图像。
是否有人能给我建议?
我正在尝试在画布上开发一个应用程序,我在画布上绘制了一个位图。绘制完成后,我正在尝试将其转换为位图图像。
是否有人能给我建议?
建议取决于你想要做什么。
如果您担心控件绘制所花费的时间太长,并且想要绘制到位图中,以便可以通过位图进行blit而不是通过画布重新绘制,则不需要双重猜测平台-控件自动缓存其绘图到临时位图中,甚至可以使用getDrawingCache()
从控件中获取它们。
如果您想使用画布绘制位图,通常的步骤是:
Bitmap.createBitmap()
创建正确大小的位图Canvas(Bitmap)
构造函数创建指向该位图的画布实例你可以创建一个新的Bitmap
,例如:
Bitmap myBitmap = new Bitmap((int)Width, (int)Height, Config.RGB_565)
其中width
和height
与你的画布大小相同。
接下来,使用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 );
其他例子:
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;
}
以下是将画布转换为位图并存储到相册或特定文件夹的步骤。
注意:确保您已授予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
Create reference of parent layout
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
To store it into gallery
final String imagename = UUID.randomUUID().toString() + ".png";
MediaStore.Images.Media.insertImage(getContentResolver(), linearLayout .getDrawingCache(), imagename, "drawing");
To convert into bitmap
linearLayout.setDrawingCacheEnabled(true);
linearLayout.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(linearLayout.getDrawingCache());