把TextView转化为Bitmap以及压缩Bitmap的方法

写一个安卓小程序的时候发现我们需要显示一个气泡,气泡里面有图片和文字,这些都是动态改变的,所有我们绘制的时候就会比较复杂,但是我们把这个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
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值