【发布时间】:2011-04-30 03:33:25
【问题描述】:
我正在尝试在画布上开发应用程序,我正在画布上绘制位图。绘制后,我正在尝试转换为位图图像。
谁能给我一个建议?
【问题讨论】:
-
您已经获得了一个位图对象,或者您想将此画布保存到位图文件中?
标签: android bitmap android-canvas
我正在尝试在画布上开发应用程序,我正在画布上绘制位图。绘制后,我正在尝试转换为位图图像。
谁能给我一个建议?
【问题讨论】:
标签: android bitmap android-canvas
建议取决于您要做什么。
如果您担心您的控件需要很长时间来绘制,并且您想绘制到位图以便可以位图而不是通过画布重新绘制,那么您不要 em> 想要对平台进行双重猜测 - 控件会自动将其绘图缓存到临时位图,甚至可以使用 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());
【讨论】: