Radiobutton 设置drawtop图片大小

来源:互联网 发布:java中间件启动spring 编辑:程序博客网 时间:2024/05/16 05:55

首先从资源文件中获取图片资源

//获取资源文件图片,设置大小    public static Bitmap getMyBitmap(Context context, int id,int w, int h){        Bitmap oldbmp = BitmapFactory.decodeResource(context.getResources(), id);        if(oldbmp!=null){                int width = oldbmp.getWidth();//获取的是像素                 int height = oldbmp.getHeight();                Log.i("单位", "宽:"+width+"高度:"+height);                Matrix matrix = new Matrix();                float scaleWidth = ((float) w / width);                float scaleHeight = ((float) h / height);                matrix.postScale(scaleWidth, scaleHeight);                Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height, matrix, true);                return newbmp;        }        else{                return null;        }}
单位转换工具类
import android.content.Context;  public class DensityUtil {        /**      * 根据手机的分辨率从 dp 的单位 转成为 px(像素)      */      public static int dip2px(Context context, float dpValue) {          final float scale = context.getResources().getDisplayMetrics().density;          return (int) (dpValue * scale + 0.5f);      }        /**      * 根据手机的分辨率从 px(像素) 的单位 转成为 dp      */      public static int px2dip(Context context, float pxValue) {          final float scale = context.getResources().getDisplayMetrics().density;          return (int) (pxValue / scale + 0.5f);      }  }  

实现代码

radio_first = (RadioButton) findViewById(R.id.radio_first);int sp=DensityUtil.dip2px(this, 30);//转换为像素        Log.i("单位", "转换的像素:"+sp);Drawable  dr_first=new BitmapDrawable( Utils.getMyBitmap(this, R.drawable.nav_yi,sp , sp));//位图转换为drawabledr_first.setBounds(0, 0, dr_first.getMinimumWidth(), dr_first.getMinimumHeight());         radio_first.setCompoundDrawables(null,dr_first,null , null);//radioabutton 设置
但是我建议不要使用这种方法,美工能把图片做到最适合的尺寸,就最好,这种模式性能不高,而且很难设置适合的放大缩小比例。

0 0
原创粉丝点击