写一个安卓小程序的时候发现我们需要显示一个气泡,气泡里面有图片和文字,这些都是动态改变的,所有我们绘制的时候就会比较复杂,但是我们把这个Bitmap用TextView表示呢,就会发现这样表示是非常方便的,只需要在布局文件中加上个TextView,然后里面的东西自己设置,然后我们在MainActivity中添加个buildTextViewBitmap方法(如下)就好了。
activity_main.xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/id_age_and_gender"
android:drawableLeft="@drawable/male"
android:background="@drawable/hint"
android:visibility="invisible"
android:textColor="#ffff00ff"
android:textSize="22sp"
android:gravity="center"
/>
MainActivity.java:
private Bitmap buildTextViewBitmap(int age, boolean isMale) {
TextView tv = mWaitting.findViewById(R.id.id_age_and_gender);
tv.setText(age+"");
if(isMale){
tv.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.male), null, null, null);//设置Drawable显示在text的左、上、右、下位置
}
else{
tv.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.female), null, null, null);
}
tv.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(tv.getDrawingCache());
tv.destroyDrawingCache();
return bitmap;
}
有时候传递上去的图片有大小限制的时候我们就会发现需要对Bitmap进行压缩,下面就是一个对图片进行压缩的方法。
private void resizePhoto() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//true为不加载图片,只有宽高这类的数据
BitmapFactory.decodeFile(mCurreatPhotoStr,options);
double ratio = Math.max(options.outWidth*1.0d/1024f,options.outHeight*1.0d/1024f);//求出压缩比例(1024是代表不能超过1024,这个我们可以自己调节)
options.inSampleSize = (int) Math.ceil(ratio);//把压缩比例传入options中
options.inJustDecodeBounds = false;
mPhotoImg = BitmapFactory.decodeFile(mCurreatPhotoStr,options);//压缩图片,mPhoto是压缩过后的Bitmap
}