老规矩 效果图先上 ,
下面直接上代码
public class ScoreView extends View { private Bitmap defaultImg,setImg ; private int defaultImgId = R.mipmap.star_1 ,setImgId = R.mipmap.star; private int inpadding =10; // 星星之间的间距 private int starNum = 5 ; private int imgsize ; public ScoreView(Context context) { this(context,null); } public ScoreView(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public ScoreView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ScoreView); inpadding = (int) array.getDimension(R.styleable.ScoreView_inpadding,inpadding); imgsize = (int) array.getDimension(R.styleable.ScoreView_imgsize,imgsize); starNum = array.getInt(R.styleable.ScoreView_starNum,starNum); defaultImgId = array.getResourceId(R.styleable.ScoreView_defaultImg,defaultImgId); setImgId = array.getResourceId(R.styleable.ScoreView_setImg,setImgId); defaultImg = BitmapFactory.decodeResource(getResources(),defaultImgId); setImg = BitmapFactory.decodeResource(getResources(),setImgId); array.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = defaultImg.getWidth()*starNum+((starNum-1)*inpadding); int heigt = defaultImg.getHeight(); setMeasuredDimension(width,heigt); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (int i = 0; i < starNum; i++) { int x = i*defaultImg.getWidth()+(i*inpadding); if(mCurrentNumber>i){ canvas.drawBitmap(setImg,x,0,null); }else { canvas.drawBitmap(defaultImg,x,0,null); } } } private int mCurrentNumber ; // 需要绘制选中图片的数量 @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_UP: float slidingLength = event.getX(); // 获取到当前触摸的位置 event.getRawX() 这个是相对屏幕的位置 int number = Math.round(slidingLength/(defaultImg.getWidth()+inpadding)); // 向上取整 Log.i("当前位置 ","---"+mCurrentNumber); if(number>starNum){ number = starNum ; } if(mCurrentNumber ==number){ return true; } mCurrentNumber = number ; invalidate(); } return true; // 如果返回false move手势执行不到 } }
需要的 自定义属性文件
<declare-styleable name="ScoreView"> <attr name="defaultImg" format="reference"/> <attr name="setImg" format="reference"/> <attr name="inpadding" format="dimension"/> <attr name="starNum" format="integer"/> <attr name="imgsize" format="dimension"/> </declare-styleable>