2016-06-24 51 views
0

我使用下面的代碼獲得可繪製的完美效果,但高度和寬度在所有屏幕上不同,我如何獲得常用高度(大小= 34)和寬度(大小= 34)適用於所有設備。Android適用於所有分辨率的常見高度和寬度

public Drawable getDrawable(String source) { 
     int height = 34, 
       width = 34; 
     LevelListDrawable d = new LevelListDrawable(); 
     int id = _context.getResources().getIdentifier(source, "drawable", _context.getPackageName()); 
     Drawable empty = _context.getResources().getDrawable(id); 
     d.addLevel(0, 0, empty); 
     d.setBounds(0, 0, height, width); 
     return d; 
    } 

回答

0

您需要在整個屏幕密度上使用與密度無關的像素以獲得通用尺寸。

int dips = 34; 
Resources r = getResources(); 
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dips, r.getDisplayMetrics()); 

,然後使用等效像素設定的寬度和高度,

d.setBounds(0, 0, px, px); 
+0

謝謝你的工作...... –

0

你將需要採取設備屏幕密度在帳戶。使用以下解決方案

public Drawable getDrawable(String source) { 
    int height = 34, width = 34; 
    // Scale width and height based on screen density. 
    int scaledHeigh = (int) Math.ceil(height * _context.getResources().getDisplayMetrics().density); 
    int scaledHeigh = (int) Math.ceil(height * _context.getResources().getDisplayMetrics().density); 

    LevelListDrawable d = new LevelListDrawable(); 
    int id = _context.getResources().getIdentifier(source, "drawable", _context.getPackageName()); 
    Drawable empty = _context.getResources().getDrawable(id); 
    d.addLevel(0, 0, empty); 
    // Use the scaled width and height. 
    d.setBounds(0, 0, scaledHeight, scaledWidth); 
    return d; 
} 
相關問題