项目需要,顺手写了一个半圆按钮,记录下来,供新手学习
代码如下:
<span style="white-space:pre"></span>public class HalfCircleButton extends Button {
<span style="white-space:pre"> </span>public HalfCircleButton(Context context, AttributeSet attrs, int defStyle) {
<span style="white-space:pre"> </span>super(context, attrs, defStyle);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public HalfCircleButton(Context context, AttributeSet attrs) {
<span style="white-space:pre"> </span>super(context, attrs);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public HalfCircleButton(Context context) {
<span style="white-space:pre"> </span>super(context);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>protected void onDraw(Canvas canvas) {
<span style="white-space:pre"> </span>Paint paint = new Paint();
<span style="white-space:pre"> </span>// 设置画笔为填充样式
<span style="white-space:pre"> </span>paint.setStyle(Style.FILL);
<span style="white-space:pre"> </span>// 设置画笔颜色
<span style="white-space:pre"> </span>paint.setColor(Color.parseColor("#568330"));
<span style="white-space:pre"> </span>// 消除锯齿
<span style="white-space:pre"> </span>paint.setAntiAlias(true);
<span style="white-space:pre"> </span>// 做画范围
<span style="white-space:pre"> </span>RectF rectF = new RectF();
<span style="white-space:pre"> </span>//确定起始坐标和宽高,这里高度为原来的2倍,这样圆点就在矩形的下边线上 了
<span style="white-space:pre"> </span>rectF.set(0, 0, this.getWidth(), this.getHeight() * 2);
<span style="white-space:pre"> </span>//起点与终点
<span style="white-space:pre"> </span>float startAngle = -180;
<span style="white-space:pre"> </span>float sweepAngle = 180;
<span style="white-space:pre"> </span>canvas.drawArc(rectF, startAngle, sweepAngle, false, paint);
<span style="white-space:pre"> </span>this.setBackgroundColor(Color.TRANSPARENT);
<span style="white-space:pre"> </span>//注意这里,这是button自己的绘画,需要放到我们的代码之后,否则,button原有的样式会被覆盖
<span style="white-space:pre"> </span>super.onDraw(canvas);
<span style="white-space:pre"> </span>}
}
在布局文件中的使用
<com.clly.filemaster.views.HalfCircleButton
android:layout_width="140dp"
android:layout_height="70dp"
android:layout_gravity="center_horizontal"
android:paddingTop="30dp"
android:text="上传文件"
android:textColor="#c6ff95" />