我用这段代码下载图像:
ImageGetter imageGetter = new ImageGetter() {
@Override
public Drawable getDrawable(String source) {
Drawable drawable = null;
try {
URL url = new URL(source);
String path = Environment.getExternalStorageDirectory().getPath()+"/Android/data/com.my.pkg/"+url.getFile();
File f=new File(path);
if(!f.exists()) {
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
f=new File(f.getParent());
f.mkdirs();
FileOutputStream os = new FileOutputStream(path);
byte[] buffer = new byte[4096];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.close();
is.close();
}
drawable = Drawable.createFromPath(path);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Throwable t) {
t.printStackTrace();
}
if(drawable != null) {
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}
return drawable;
}
};
Run Code Online (Sandbox Code Playgroud)
此图片的大小为20x20.但是drawable.getIntrinsicWidth()和drawable.getIntrinsicHeight()返回27.并且图像看起来更大.我怎么解决它?
我尝试了代码形式的答案,但没有奏效.所以相反,我使用下面的代码,它工作正常.
DisplayMetrics dm = context.getResources().getDisplayMetrics();
Options options=new Options();
options.inDensity=dm.densityDpi;
options.inScreenDensity=dm.densityDpi;
options.inTargetDensity=dm.densityDpi;
Bitmap bmp = BitmapFactory.decodeFile(path,options);
drawable = new BitmapDrawable(bmp, context.getResources());
Run Code Online (Sandbox Code Playgroud)
小智 5
BitmapDrawable必须缩放位图以补偿不同的屏幕密度.
如果需要它来绘制像素像素,请尝试将Drawable的源密度和目标密度设置为相同的值.为此,您需要稍微不同的对象才能使用.
代替
drawable = Drawable.createFromPath(path);
Run Code Online (Sandbox Code Playgroud)
使用
Bitmap bmp = BitmapFactory.decodeFile(path);
DisplayMetrics dm = context.getResources().getDisplayMetrics();
bmp.setDensity(dm.densityDpi);
drawable = new BitmapDrawable(bmp, context.getResources());
Run Code Online (Sandbox Code Playgroud)
如果您没有上下文(您应该),您可以使用应用程序上下文,请参阅例如在任何地方使用应用程序上下文?
由于位图的密度设置为资源密度,即实际设备的屏幕密度,因此应绘制而不进行缩放.
| 归档时间: |
|
| 查看次数: |
5607 次 |
| 最近记录: |