我正在使用下面的代码来获得可绘制的完美作品,但高度和宽度在所有屏幕上都有所不同如何为所有设备获得通用高度(尺寸= 34)和宽度(尺寸= 34)..
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 :(得分:0)
您需要在屏幕密度范围内使用与密度无关的像素作为通用尺寸。
int dips = 34;
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dips, r.getDisplayMetrics());
然后使用等效像素设置宽度和高度,
d.setBounds(0, 0, px, px);
答案 1 :(得分: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;
}