0
我嘗試爲我的應用程序製作一個自定義RatingBar,該應用程序對每個4星都有不同的圖像。 使用以下onDraw方法,它對我的手機非常有用。RatingBar(或位置和大小)中星星的邊距/填充?
public class MyBar extends RatingBar {
private int[] starArrayColor = { R.drawable.star_1_color, R.drawable.star_2_color, R.drawable.star_3_color, R.drawable.star_4_color };
private int[] starArrayGrey = { R.drawable.star_1_grey, R.drawable.star_2_grey, R.drawable.star_3_grey, R.drawable.star_4_grey };
(...)
@Override
protected synchronized void onDraw(Canvas canvas) {
int stars = getNumStars();
float rating = getRating();
float x = 10;
for (int i=0;i<stars;i++) {
Bitmap bitmap;
Resources res = getResources();
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
if ((int) rating-1 == i) {
paint.setAlpha(255);
bitmap = BitmapFactory.decodeResource(res, starArrayColor[i]);
} else {
paint.setAlpha(70);
bitmap = BitmapFactory.decodeResource(res, starArrayGrey[i]);
}
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 75, 75, true);
canvas.drawBitmap(scaled, x, 12, paint);
x += 96;
}
}
}
但是x/y位置和圖像大小的「計算」成了!它只是試驗和錯誤,以獲得正確的座標...
我如何計算位置/大小等,讓它在每個設備上正常工作?
在AbsSeekBar/Progressbar的來源中,我找到了一些名爲mPaddingTop,mPaddingBottom等的變量。有沒有辦法獲得這些值?
你能解釋一下嗎?我應該調用哪個對象getWidth/getHeight?我需要將這顆星作爲一個對象,但是我從哪裏得到這些? – Oliver 2013-02-15 19:23:58
要繪製的位圖對象。雖然由於您通過createScaledBitmap從原始尺寸縮放了它,但您知道它將精確到75x75,因此您無需猜測。對於項目之間的填充量,您也可以選擇。最好的辦法是選擇一個尺寸看起來不錯的尺寸,然後乘以系統dpi來獲取像素數量,並在每個元素之間使用它。 – 2013-02-15 19:33:12
我的位圖的大小並不重要。 75x75是我需要計算的,因爲它只能在我的手機上使用。但不在其他設備上。 – Oliver 2013-02-15 19:58:53