当前位置:编程学习 > wap >>

求助:createFromPath到底做了什么?

关于设置背景图片,依据图片来源,主要有两种方法:
ImageView iv = new ImageView(mContext);
iv.setBackgroundResource(R.drawable.XXX)是采用应用的静态图片资源id做参数.
如果图片是网络读取,就需要把图片下载到本地,并使用Drawable.createFromPath(图片在SD卡路径)将图片转为drawable对象,
通过 iv.setBackground(drawable)来完成设定.

现在的问题是,同样的图片,采用iv.setBackgroundResource(id)能正常显示.
但是使用Drawable.createFromPath(图片在SD卡路径),好像系统会自动将图片尺寸会根据DENSITY做缩放. 最终导致显示出来的图片是变形的.
而且通过虾米呐的方法来看,图片尺寸确实被缩小了一半.
drawable.getIntrinsicWidth()
drawable.getIntrinsicHeight()

应该可以确定不是setBackgroundResource和setBackground不同导致的,从源码看,他们原理是一致的.

public void setBackgroundResource(int resid) {
    if (resid != 0 && resid == mBackgroundResource) {
        return;
    }

    Drawable d= null;
    if (resid != 0) {
        d = mResources.getDrawable(resid);
    }
    setBackground(d);

    mBackgroundResource = resid;
}

public void setBackground(Drawable background) {
    //noinspection deprecation
    setBackgroundDrawable(background);
}
求大神指导,如何用createFromPath得到原尺寸的图片. --------------------编程问答-------------------- 算了 自己查得了。

public static Drawable createFromPath(String pathName) {
         if (pathName == null) {
             return null;
         }
         Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, pathName);

         try {
             Bitmap bm = BitmapFactory.decodeFile(pathName);
             if (bm != null) {
                 return drawableFromBitmap(null, bm, null, null, null, pathName);
             }
         } finally {
             Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
         }
         return null;
     }
--------------------编程问答--------------------

private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np,

            Rect pad, Rect layoutBounds, String srcName) {

        if (np != null) {
            return new NinePatchDrawable(res, bm, np, pad, layoutBounds, srcName);
        }
        return new BitmapDrawable(res, bm);
    }

--------------------编程问答-------------------- Create drawable from a bitmap, setting initial target density based on the display metrics of the resources. 

    public BitmapDrawable(Resources res, Bitmap bitmap) {
        this(new BitmapState(bitmap), res);
        mBitmapState.mTargetDensity = mTargetDensity;
    }
补充:移动开发 ,  Android
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,