如何從InputStream(資產,文件系統)加載drawable並基於屏幕分辨率hdpi,mdpi或ldpi動態調整其大小?Android負載以編程方式繪製並調整大小
原始圖像是在hdpi中,我只需要調整大小爲mdpi和ldpi。
有誰知道Android如何動態調整/ res中的drawables的大小?
如何從InputStream(資產,文件系統)加載drawable並基於屏幕分辨率hdpi,mdpi或ldpi動態調整其大小?Android負載以編程方式繪製並調整大小
原始圖像是在hdpi中,我只需要調整大小爲mdpi和ldpi。
有誰知道Android如何動態調整/ res中的drawables的大小?
發現:
/**
* Loads image from file system.
*
* @param context the application context
* @param filename the filename of the image
* @param originalDensity the density of the image, it will be automatically
* resized to the device density
* @return image drawable or null if the image is not found or IO error occurs
*/
public static Drawable loadImageFromFilesystem(Context context, String filename, int originalDensity) {
Drawable drawable = null;
InputStream is = null;
// set options to resize the image
Options opts = new BitmapFactory.Options();
opts.inDensity = originalDensity;
try {
is = context.openFileInput(filename);
drawable = Drawable.createFromResourceStream(context.getResources(), null, is, filename, opts);
} catch (Throwable e) {
// handle
} finally {
if (is != null) {
try {
is.close();
} catch (Throwable e1) {
// ingore
}
}
}
return drawable;
}
使用這樣的:
loadImageFromFilesystem(context, filename, DisplayMetrics.DENSITY_MEDIUM);
Unfortunatley此代碼不適用於HTC Desire HD和HTC Evo。在此處查看解決方案:http://stackoverflow.com/questions/7747089/exception-in-drawable-createfromresourcestream-htc-only/9195531#9195531 – peceps 2012-02-08 14:46:47
如果你想顯示的圖像,但不幸的是這個形象是大尺寸的,讓例子,你要顯示的圖像以30乘30的格式,然後檢查它的大小,如果它大於你的要求大小,然後除以你的數量(在這裏是30 * 30),然後你再次拿到並用來再次分割圖像區域。
drawable = this.getResources().getDrawable(R.drawable.pirImg);
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
if (width > 30)//means if the size of an image is greater than 30*30
{
width = drawable.getIntrinsicWidth()/30;
height = drawable.getIntrinsicWidth()/30;
}
drawable.setBounds(
0, 0,
drawable.getIntrinsicWidth()/width,
drawable.getIntrinsicHeight()/height);
//and now add the modified image in your overlay
overlayitem[i].setMarker(drawable)
後加載您的圖片,並將其設置爲imageview的 你可以使用layoutparamsto大小的圖像match_parent
這樣
android.view.ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
layoutParams.width =MATCH_PARENT;
layoutParams.height =MATCH_PARENT;
imageView.setLayoutParams(layoutParams);
出於好奇,有什麼理由不預上漿它(爲'mdpi'和'ldpi')並在'res'目錄中鏈接到它? – 2012-01-12 15:45:58
從網絡下載的圖像。我可以在服務器上執行預處理,但下載速度會變慢。 – peceps 2012-01-12 15:48:42