2016-06-24 107 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; 
} 
相关问题