android Bitmap
来源:互联网 发布:ubuntu 实时聊天工具 编辑:程序博客网 时间:2024/05/16 09:48
1)从android的资源文件夹layout中加载xml布局文件,并把布局文件映射为Bitmap
main.xml文件如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="256px"
- android:layout_height="256px">
- <TextView android:layout_width="wrap_content" android:id="@+id/city"
- android:layout_height="wrap_content" android:textSize="20px"
- android:textColor="#ffffff" android:shadowColor="#0000AA"
- android:shadowDx="0" android:shadowDy="-2" android:shadowRadius="0.1"
- android:layout_gravity="right" android:layout_marginRight="5px" />
- </LinearLayout>
java代码中的处理,方法一:
-
- LayoutInflater factory = LayoutInflater.from(context);
- View view = factory.inflate(R.layout.main, null);
-
- TextView city = (TextView) view.findViewById(R.id.city);
-
- city.setText("xml中的textview");
-
- view.setDrawingCacheEnabled(true);
-
- view.measure(MeasureSpec.makeMeasureSpec(256, MeasureSpec.EXACTLY),
- MeasureSpec.makeMeasureSpec(256, MeasureSpec.EXACTLY));
-
- view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
-
- view.buildDrawingCache();
- Bitmap bitmap = view.getDrawingCache();
java代码中的处理,方法二:
-
- LayoutInflater factory = LayoutInflater.from(context);
- View view = factory.inflate(R.layout.main, null);
-
- TextView city = (TextView) view.findViewById(R.id.city);
-
- city.setText("xml中的textview");
-
- view.measure(MeasureSpec.makeMeasureSpec(256, MeasureSpec.EXACTLY),
- MeasureSpec.makeMeasureSpec(256, MeasureSpec.EXACTLY));
-
- view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
-
- Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
- Bitmap.Config.RGB_565);
-
- Canvas canvas = new Canvas(bitmap);
-
- view.draw(canvas);
2)Bitmap转换为byte[]数组
方法一:
- private byte[] Bitmap_To_Bytes(Bitmap bitmap){
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
- return baos.toByteArray();
- }
方法二:
- public static byte[] readStream(InputStream inStream) throws Exception {
- byte[] buffer = new byte[1024];
- int len = -1;
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- while ((len = inStream.read(buffer)) != -1) {
- baos .write(buffer, 0, len);
- }
- byte[] data = baos .toByteArray();
- baos .close();
- inStream.close();
- return data;
-
- }
3)设置在应用中支持32位的图像:
在onCreate()函数中加入以下两行:
- getWindow().setFormat(PixelFormat.RGBX_8888);
- BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
以使之 支持32bit的图像。
4)把drawable文件夹下的文件转成Bitmap
- Bitmap bm = BitmapFactory.decodeResource(getApplicationContext().getResources(),
- R.drawable.down);