我正在尝试在画布上开发应用程序,我正在画布上绘制位图。绘制后,我正在尝试转换为位图图像。
谁能给我一个建议?
建议取决于您要做什么。
如果您担心您的控件需要很长时间才能绘制,并且您想绘制位图以便您可以位图而不是通过画布重新绘制,那么您不想怀疑平台- 控件自动将其绘图缓存到临时位图,这些甚至可以使用从控件中获取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
创建父布局的引用
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
将其存储到图库中
final String imagename = UUID.randomUUID().toString() + ".png";
MediaStore.Images.Media.insertImage(getContentResolver(), linearLayout .getDrawingCache(), imagename, "drawing");
转换成位图
linearLayout.setDrawingCacheEnabled(true);
linearLayout.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(linearLayout.getDrawingCache());