注册

Android自定义弧型View



好久没动手玩View自定义,有点生疏了。效果如下


思路很简单,onDraw绘制弧线、绘制Text



canvas.drawArc(oval, startAngle, sweepAngle, false, paint);

canvas.drawText(integralValue, rectF.centerX(), baseline, textPaint);


draw 动画效果实现:invalidate


canvas.drawArc(oval, startAngle, i, false, paint);

if(i<sweepAngle){
i = i+10;//sweepAngle :240,所以这里+10没问题,具体细节具体修改
getHandler().postDelayed(new Runnable() {
@Override
public void run() {
invalidate();
}
},50);
}

绘制的效果差别有点大不理想,先给画笔添加抗锯齿和画笔圆角


textPaint.setAntiAlias(true);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);

drawText让文字居中对齐,一定要算好边界和baseLine



RectF rectF = new RectF(borderWidth * 2 + arcMargin, borderWidth * 2 + arcMargin, getMeasuredWidth() - arcMargin - borderWidth * 2, getMeasuredHeight() - arcMargin - borderWidth * 2);

//计算baseline
Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
float distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
float baseline = rectF.centerY() + distance;
canvas.drawText(integralValue, rectF.centerX(), baseline, textPaint);

积分商城文本背景可以用shape绘制,这里直接代码搞一个drawable


   /**
* 设置圆角背景
*
* @param
* @param radiiValue 设置图片四个角圆形半径
* @return
*/
@SuppressLint("WrongConstant")
public static GradientDrawable getBackgroundShapeDrawable(int color, float radiiValue) {
float[] radii = new float[] { radiiValue, radiiValue, radiiValue, radiiValue, radiiValue, radiiValue, radiiValue,radiiValue };
GradientDrawable drawable = new GradientDrawable();
drawable.setShape(GradientDrawable.RECTANGLE);
drawable.setGradientType(GradientDrawable.RECTANGLE);
drawable.setCornerRadii(radii);
drawable.setColor(color);
return drawable;
}

居中文字大小不能固定值,防止超出弧型,要跟据文字长度动态调整



textPaint.setTextSize(getIntegralTextSize(integralValue));

protected int getIntegralTextSize(String text) {
int flag = 80;
if (text.length() == 8) {
flag = 70;
} else if (text.length() == 9) {
flag = 60;
} else if (text.length() >= 10) {
flag = 50;
}

return flag;
}

源码就不上传了,实现起来还是不难用了十几分钟,等下班咯

1 个评论

要回复文章请先登录注册