安卓运动圆环自定义View

简介: 运动圆环自定义View.gif记得这个东西原来有个同事问过我,当时正在自学自定义View和属性动画这一块,对这个功能也没有写过,所以就google了一下,发了几个类似效果的github项目给朋友,今天礼拜天难得有心情写写代码,所以想想实现一下这个自定义View的效果。
运动圆环自定义View.gif

记得这个东西原来有个同事问过我,当时正在自学自定义View和属性动画这一块,对这个功能也没有写过,所以就google了一下,发了几个类似效果的github项目给朋友,今天礼拜天难得有心情写写代码,所以想想实现一下这个自定义View的效果。
首先,我们从这个gif的效果图中就可以得知这个自定义View我们需要哪些自定义属性,内部圆环的颜色、外部圆环的颜色、圆环的宽度、字体的大小、颜色,话不多说,直接撸码。

        <!-- 运动圆环自定义属性 -->
    <declare-styleable name="MotionCrcle">
        <attr name="outerCrcleColor" format="color"></attr>
        <attr name="innerCrcleColor" format="color"></attr>
        <attr name="crcleTextColor" format="color"></attr>
        <attr name="crcleTextSize" format="integer"></attr>
        <attr name="crcleWidth" format="integer"></attr>
    </declare-styleable>
/**
 * Created by Administrator on 2018/5/13.
 * 运动圆环自定义View
 */

public class MotionCrcle extends View {
    /**
     * 外部圆环颜色
     */
    private int mOuterColor = Color.BLUE;
    /**
     * 里面圆环颜色
     */
    private int mInnerColor = Color.RED;
    /**
     * 跑步数的文字大小
     */
    private int mTextSize = 30;
    /**
     * 跑步文字的颜色
     */
    private int mTextColor = Color.BLACK;
    /**
     * 圆环的宽度
     */
    private int mCrcleWidth = 45;
    private Paint mOuterPaint, mInnerPaint, mTextPaint;
    private float mMaxSteps = 0;
    private int mCurrentSteps = 0;
    public MotionCrcle(Context context) {
        this(context, null);
    }

    public MotionCrcle(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MotionCrcle(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MotionCrcle);
        mOuterColor = array.getColor(R.styleable.MotionCrcle_outerCrcleColor, mOuterColor);
        mInnerColor = array.getColor(R.styleable.MotionCrcle_innerCrcleColor, mInnerColor);
        mCrcleWidth = array.getInt(R.styleable.MotionCrcle_crcleWidth, mCrcleWidth);
        mTextColor = array.getColor(R.styleable.MotionCrcle_crcleTextColor, mTextColor);
        mTextSize = array.getInt(R.styleable.MotionCrcle_crcleTextSize, mTextSize);
        initPaint();
        array.recycle();
    }

    public synchronized void setmMaxSteps(float mMaxSteps) {
        this.mMaxSteps = mMaxSteps;
    }

    public synchronized void setmCurrentSteps(int mCurrentSteps) {
        this.mCurrentSteps = mCurrentSteps;
        invalidate();
    }

    private void initPaint() {
        mOuterPaint = new Paint();
        mOuterPaint.setAntiAlias(true);
        mOuterPaint.setStrokeWidth(mCrcleWidth);
        mOuterPaint.setStrokeCap(Paint.Cap.ROUND);
        mOuterPaint.setStyle(Paint.Style.STROKE);
        mOuterPaint.setColor(mOuterColor);

        mInnerPaint = new Paint();
        mInnerPaint.setAntiAlias(true);
        mInnerPaint.setStrokeWidth(mCrcleWidth);
        mInnerPaint.setStrokeCap(Paint.Cap.ROUND);
        mInnerPaint.setStyle(Paint.Style.STROKE);
        mInnerPaint.setColor(mInnerColor);

        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(mTextSize);
        mTextPaint.setColor(mTextColor);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if(width != height){
            /**
             * 因为运动圆环是一个正方形,所以我们要设置一个最小值作为View的长度
             */
            int min = Math.min(width, height);
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, MeasureSpec.EXACTLY);
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(min, MeasureSpec.EXACTLY);
            setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
       //因为圆环本身是具有宽度的,所以我们这里左边的顶点要往右mCrcleWidth个距离,右边底部的点要往左,所以要减去mCrcleWidth
        RectF recf = new RectF(mCrcleWidth, mCrcleWidth,
                getWidth() - mCrcleWidth, getHeight() - mCrcleWidth);
      //135是外部圆环的初始角度,270是所画的总角度数
        canvas.drawArc(recf, 135, 270, false, mOuterPaint);
        if(mCurrentSteps == 0){
            return;
        }
      //算出当前步数是最大步数的比值
        float angle = mCurrentSteps / mMaxSteps;
        canvas.drawArc(recf, 135, 270 * angle, false, mInnerPaint);
        String stepText = mCurrentSteps+"";
        Rect bounds = new Rect();
      //算出步数文字的baseLine,也就是基准线
        mTextPaint.getTextBounds(stepText, 0, stepText.length(), bounds);
        int x = getWidth() / 2 - bounds.width() / 2;
        Paint.FontMetricsInt metrices = mTextPaint.getFontMetricsInt();
        int diffY = (metrices.bottom - metrices.top) / 2 - metrices.bottom;
        int baseLine = getHeight() / 2 + diffY;
        canvas.drawText(stepText, x, baseLine, mTextPaint);
    }

}
文字基准线说明图.jpg

文字的绘制和画圆画弧不一样,其实仔细想想也明白,如果绘制按照左上角开始的话是不现实的,因为文字不可能是简单的顶部或底部对其,应该是重心对齐,简单说就是基准线,所以代码中基准线的算法是bottom-top再除以2减去bottom,以基准线开始绘制,top就是负数,bottom是正数。

public class MainActivity extends AppCompatActivity {

    private Button mBtn;
    private baohuo.rzj.com.myapplication.Views.MotionCrcle mCrcle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtn = (Button) findViewById(R.id.btn);
        mCrcle = (MotionCrcle) findViewById(R.id.motion_crcle);
        mCrcle.setmMaxSteps(10000);
        final ValueAnimator animator = ObjectAnimator.ofFloat(0,4500);
        animator.setDuration(2000);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float value = (float) valueAnimator.getAnimatedValue();
                mCrcle.setmCurrentSteps((int) value);
            }
        });
        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                animator.start();
            }
        });
    }
}

以上是Activity的代码,非常简单,不做解释,这个值得一提的是,我在写的时候内部圆环一直没有绘制,文字在不断变化,通过debug发现,我把步数最大值和当前步数设置为int,一个小的int除以大的int的到的只有0,所以我把最大步数改为float,这样得出的值就有小数位,最后附上xml代码。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="baohuo.rzj.com.myapplication.MainActivity">
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:text="运动圆环开启"
        android:gravity="center"/>
    <baohuo.rzj.com.myapplication.Views.MotionCrcle
        android:id="@+id/motion_crcle"
        android:layout_below="@+id/btn"
        android:layout_width="200dp"
        android:layout_height="200dp"
        app:outerCrcleColor="@color/colorPrimary"
        app:innerCrcleColor="@color/colorAccent"
        app:crcleTextColor="@color/colorPrimaryDark"
        app:crcleTextSize="40"
        app:crcleWidth="20"/>


</RelativeLayout>
相关文章
|
15天前
|
存储 Shell Android开发
基于Android P,自定义Android开机动画的方法
本文详细介绍了基于Android P系统自定义开机动画的步骤,包括动画文件结构、脚本编写、ZIP打包方法以及如何将自定义动画集成到AOSP源码中。
40 2
基于Android P,自定义Android开机动画的方法
|
13天前
|
供应链 物联网 区块链
未来触手可及:探索新兴技术的趋势与应用安卓开发中的自定义视图:从基础到进阶
【8月更文挑战第30天】随着科技的飞速发展,新兴技术如区块链、物联网和虚拟现实正在重塑我们的世界。本文将深入探讨这些技术的发展趋势和应用场景,带你领略未来的可能性。
|
14天前
|
测试技术 Android开发 Python
探索软件测试的艺术:从基础到高级安卓应用开发中的自定义视图
【8月更文挑战第29天】在软件开发的世界中,测试是不可或缺的一环。它如同艺术一般,需要精细的技巧和深厚的知识。本文旨在通过浅显易懂的语言,引领读者从软件测试的基础出发,逐步深入到更复杂的测试策略和工具的使用,最终达到能够独立进行高效测试的水平。我们将一起探索如何通过不同的测试方法来确保软件的质量和性能,就像艺术家通过不同的色彩和笔触来完成一幅画作一样。
|
3天前
|
Android开发
Android中SurfaceView的双缓冲机制和普通View叠加问题解决办法
本文介绍了 Android 平台上的 SurfaceView,这是一种高效的图形渲染控件,尤其适用于视频播放、游戏和图形动画等场景。文章详细解释了其双缓冲机制,该机制通过前后缓冲区交换来减少图像闪烁,提升视觉体验。然而,SurfaceView 与普通 View 叠加时可能存在 Z-Order 不一致、同步问题及混合渲染难题。文中提供了使用 TextureView、调整 Z-Order 和创建自定义组合控件等多种解决方案。
26 9
|
7天前
|
Android开发 容器
Android经典实战之如何获取View和ViewGroup的中心点
本文介绍了在Android中如何获取`View`和`ViewGroup`的中心点坐标,包括计算相对坐标和屏幕上的绝对坐标,并提供了示例代码。特别注意在视图未完成测量时可能出现的宽高为0的问题及解决方案。
18 7
|
13天前
|
XML 搜索推荐 Android开发
安卓开发中的自定义View组件实践
【8月更文挑战第30天】探索Android世界,自定义View是提升应用界面的关键。本文以简洁的语言带你了解如何创建自定义View,从基础到高级技巧,一步步打造个性化的UI组件。
|
15天前
|
Android开发
Android在rootdir根目录创建自定义目录和挂载点的方法
本文介绍了在Android高通平台的根目录下创建自定义目录和挂载点的方法,通过修改Android.mk文件并使用`LOCAL_POST_INSTALL_CMD`变量在编译过程中添加目录,最终在ramdisk.img的系统根路径下成功创建了`/factory/bin`目录。
35 1
|
27天前
|
API Android开发 开发者
Android经典实战之使用ViewCompat来处理View兼容性问题
本文介绍Android中的`ViewCompat`工具类,它是AndroidX库核心部分的重要兼容性组件,确保在不同Android版本间处理视图的一致性。文章列举了设置透明度、旋转、缩放、平移等功能,并提供了背景色、动画及用户交互等实用示例。通过`ViewCompat`,开发者可轻松实现跨版本视图操作,增强应用兼容性。
67 5
|
5天前
|
前端开发 搜索推荐 Android开发
探索安卓开发中的自定义视图##
【9月更文挑战第6天】 在安卓应用开发的世界里,自定义视图如同绘画艺术中的色彩,它们为界面设计增添了无限可能。通过掌握自定义视图的绘制技巧,开发者能够创造出既符合品牌形象又提升用户体验的独特界面元素。本文将深入浅出地介绍如何从零开始构建一个自定义视图,包括基础框架搭建、关键绘图方法实现、事件处理机制以及性能优化策略。准备好让你的安卓应用与众不同了吗?让我们开始吧! ##
|
17天前
|
前端开发 Android开发 开发者
安卓开发中的自定义视图:构建你的第一个控件
【8月更文挑战第26天】在安卓开发的浩瀚海洋中,自定义视图是一块充满魔力的乐土。它不仅是开发者展示创造力的舞台,更是实现独特用户体验的关键。本文将带你步入自定义视图的世界,从基础概念到实战应用,一步步教你如何打造自己的第一个控件。无论你是初学者还是有经验的开发者,这篇文章都将为你的开发之旅增添新的风景。