由于项目需要,很久之前自定义了一组星星视图,用于表示星级难度。也可以将星星改为勾号,圆圈等。
项目地址:https://github.com/Mingyueyixi/StarView
项目预览:
主要思路:
1.获取星星bitmap,根据设置的星星数量,调整View的宽度,并绘制。
2.直接使用LinearLayout.addView(new ImageView())的形式。
目前采取第一种办法,第二种可以考虑未来完成。
存在问题:
1.复杂情况可能存在事件冲突。
2.未设置星星间距等属性。
主要代码:
绘制星星:
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int height = getHeight(); float top = (height-starSize)/2.0f; for (int i = 0; i < starCount; i++) { int left = i*starSize; if (starBitmap!=null) { canvas.drawBitmap(starBitmap, left, top, paint); } } }
测量方法,使之具备适应性:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); int wMode = MeasureSpec.getMode(widthMeasureSpec); int hMode = MeasureSpec.getMode(heightMeasureSpec); if (wMode == MeasureSpec.AT_MOST) {//尽可能大,对应wrap_content width = (int) (starCount*(double)starSize); }else if (wMode == MeasureSpec.EXACTLY) { starSize = (int) (width/(double)starCount); }else { width = getScreenWidth(getContext()); } if (hMode == MeasureSpec.AT_MOST) { height = starSize; }else if (wMode == MeasureSpec.EXACTLY) { starSize = (int) (width/(double)starCount); }else { height = getScreenHeight(getContext()); } setMeasuredDimension(width, height); starBitmap = BitmapUtil.drawableToBitmap(starDrawable, starSize, starSize); }
——end