安卓自定义控件-手表

1.效果展示

2.手表控件

2.1表盘实现

画圆形表盘的条件

float centerX = getWidth() / 2.0f;//圆心X坐标
float centerY = getWidth() / 2.0f;//圆心Y坐标
float radius = getWidth() / 2.0f - 10;//半径(1/2宽稍微偏移一点,给圆盘留一些绘制宽度)

用canvas绘制圆形表盘

public void drawCircle(float cx, float cy, float radius, @NonNull Paint paint);

Draw the specified circle using the specified paint. If radius is <= 0, then nothing will be
drawn. The circle will be filled or framed based on the Style in the paint.

@param cx The x-coordinate of the center of the circle to be drawn
@param cy The y-coordinate of the center of the circle to be drawn
@param radius The radius of the circle to be drawn
@param paint The paint used to draw the circle
canvas.drawCircle(centerX, centerY, radius, paint);

2.2刻度盘实现

用path画线来实现,从(width/2, height开始画,大刻度和小刻度通过偏移量和角度来控制)

int offset = 50;//默认偏移(绘制小刻度的默认长度)
if (angle == 0 || angle == 90 || angle == 180 || angle == 270) {
    offset = 100;//分别是12点,3点,6点,9点的大刻度长度
}

path.moveTo(centerX, getHeight() - 10); //从视图宽度的1/2,底部开始绘制
path.lineTo(centerX, getHeight() - 10 - offset) //要绘制的线条长度(区分大刻度和小刻度)
matrix.setRotate(angle, centerX, centerY);//用matrix来控制旋转,这样就可以用角度绘制整个圆盘的刻度
path.transform(matrix);
canvas.drawPath(path, paint);

//表盘主要时间点文字绘制。简单的drawText操作,绘制的位置脱离表盘实现,主要是与表盘解耦
//绘制时需要注意文字的长度很高度,否则绘制出来的时间点是偏向某一方向的
String timeText;
if (angle == 0) {
    timeText = "12";
    float text_width = paint.measureText(timeText);
    canvas.drawText(timeText, centerX - text_width / 2.0f, getHeight() * 0.2f, paint);
} else if (angle == 90) {
    timeText = "3";
    Rect rect = new Rect();
    paint.getTextBounds(timeText, 0, timeText.length(), rect);
    int height = rect.height();
    canvas.drawText(timeText, getWidth() * 0.8f, centerY + height / 2.0f, paint);
} else if (angle == 180) {
    timeText = "6";
    float text_width = paint.measureText(timeText);
    canvas.drawText(timeText, centerX - text_width / 2.0f, getHeight() * 0.8f, paint);
} else if (angle == 270) {
    timeText = "9";
    Rect rect = new Rect();
    paint.getTextBounds(timeText, 0, timeText.length(), rect);
    int height = rect.height();
    canvas.drawText(timeText, getHeight() * 0.2f, centerY +
  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会写代码的猴子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值