private int measureSize(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = DensityUtils.dp2px(getContext(), 18); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; }
/** * @author: guoyazhou * @date: 2016-05-09 14:12 */ public class CircleView extends View { private static final String TAG = "CircleView"; private Paint mPaint; private Bitmap mBitmap; private float radius = DensityUtils.dp2px(getContext(), 9); // 半径 private float disX; // 位置X private float disY; // 位置Y private float angle; // 旋转的角度 private float proportion; // 根据远近距离的不同计算得到的应该占的半径比例 public CircleView(Context context) { this(context, null); } public CircleView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CircleView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mPaint = new Paint(); mPaint.setColor(getResources().getColor(R.color.color_ef5350)); mPaint.setAntiAlias(true); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(measureSize(widthMeasureSpec), measureSize(heightMeasureSpec)); } private int measureSize(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = DensityUtils.dp2px(getContext(), 18); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } @Override protected void onDraw(Canvas canvas) { canvas.drawCircle(radius, radius, radius, mPaint); if (mBitmap != null) { canvas.drawBitmap(mBitmap, null, new Rect(0, 0, 2 * (int) radius, 2 * (int) radius), mPaint); } } public float getProportion() { return proportion; } public void setProportion(float proportion) { this.proportion = proportion; } public float getAngle() { return angle; } public void setAngle(float angle) { this.angle = angle; } public float getDisX() { return disX; } public void setDisX(float disX) { this.disX = disX; } public float getDisY() { return disY; } public void setDisY(float disY) { this.disY = disY; } public void setPaintColor(int resId) { mPaint.setColor(resId); invalidate(); } public void setPortraitIcon(int resId) { mBitmap = BitmapFactory.decodeResource(getResources(), resId); invalidate(); } public void clearPortaitIcon() { mBitmap = null; invalidate(); } }