Android custom View AirConditionerView hacking

package com.example.arc.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.widget.Toast;

/**
 *                 Android custom View AirConditionerView hacking
 *
 * 声明:
 *     本人在知乎看到Android非常漂亮的自定义View文章后,因为对其绘图部分运作机制好
 * 奇,于是叫程梦真帮忙一起分析其中代码运作机制,花了两个半小时才将其整体hacking完。
 *
 *                                              2016-1-1 深圳 南山平山村 曾剑锋
 *
 *
 * 一、程序来源:
 *     1. 这种ui谁能给点思路?
 *         https://m.zhihu.com/question/38598212#answer-26400956
 *     2. github:mutexliu/ZhihuAnswer
 *         https://github.com/mutexliu/ZhihuAnswer
 *
 * 二、参考文档:
 *     1. 为什么安卓android变量命名多以小写"m"开头 ?
 *         http://www.01yun.com/mobile_development_question/20130303/194172.html
 *     2. 自定义View之onMeasure()
 *         http://blog.csdn.net/pi9nc/article/details/18764863
 *     3. MeasureSpec介绍及使用详解
 *         http://www.cnblogs.com/slider/archive/2011/11/28/2266538.html
 *     4. SweepGradient扫描渲染
 *         http://blog.csdn.net/q445697127/article/details/7867506
 *     5. SweepGradient
 *         http://developer.android.com/reference/android/graphics/SweepGradient.html
 *     6. 覆写onLayout进行layout,含自定义ViewGroup例子
 *         http://blog.csdn.net/androiddevelop/article/details/8108970
 *     7. View.MeasureSpec
 *         http://developer.android.com/reference/android/view/View.MeasureSpec.html#getMode(int)
 *
 * 三、绘图的三个步骤:
 *     1. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec);
 *     2. protected void onLayout(boolean changed, int left, int top, int right, int bottom);
 *         View中不需要实现。
 *     3. protected void onDraw(Canvas canvas);
 *
 */
public class AirConditionerView extends View {
    // 设置当前的温度
    // 这个值只能在16-28度之间,下面的private void checkTemperature(float t)方法中有限制
    private float mTemperature = 24f;
    // 画圆的paint
    private Paint mArcPaint;
    // 画上线的paint
    private Paint mLinePaint;
    // 写字的paint
    private Paint mTextPaint;

    // 这里是将控件宽度分为600份,mMinSize代表其中一份
    private float mMinSize;
    // 设置空心边框的宽度,其实就是圆弧的宽度
    private float mGapWidth;
    // 内圆半径
    private float mInnerRadius;
    // 外圆半径
    private float mRadius;
    // 中线点
    private float mCenter;

    // 圆弧矩形
    private RectF mArcRect;
    // 渐变渲染
    private SweepGradient mSweepGradient;

    // 接下来的三个构造函数是固定的写法,最后调用自己定义的的init方法
    public AirConditionerView(Context context) {
        super(context, null);
    }

    public AirConditionerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AirConditionerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        // Paint.Style.FILL              : 填充内部
        // Paint.Style.FILL_AND_STROKE    : 填充内部和描边
        // Paint.Style.STROKE            : 仅描边

        // 画圆弧的笔
        mArcPaint = new Paint();
        mArcPaint.setStyle(Paint.Style.STROKE);
        // 设置抗锯齿
        mArcPaint.setAntiAlias(true);

        // 画圆弧上的线的笔
        mLinePaint = new Paint();
        mLinePaint.setStyle(Paint.Style.STROKE);
        mLinePaint.setAntiAlias(true);
        // 设置笔的颜色
        mLinePaint.setColor(0xffdddddd);

        // 写字的笔
        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setColor(0xff64646f);
    }

    private void initSize(){
        //寬度
        mGapWidth = 56*mMinSize;
        //内圆半径
        mInnerRadius = 180*mMinSize;
        mCenter = 300*mMinSize;
        //外圆半径
        mRadius = 208*mMinSize;

        // 包含圆弧的矩形
        mArcRect = new RectF(mCenter-mRadius, mCenter-mRadius, mCenter+mRadius, mCenter+mRadius);

        // 设置渐变色、渐变位置
        /**
         * A subclass of Shader that draws a sweep gradient around a center point.
         *
         * Parameters
         * cx            The x-coordinate of the center
         * cy            The y-coordinate of the center
         * colors        The colors to be distributed between around the center. There must be at least 2 colors in the array.
         * positions    May be NULL. The relative position of each corresponding color in the colors array, beginning with 0 and ending with 1.0. If the values are not monotonic, the drawing may produce unexpected results. If positions is NULL, then the colors are automatically spaced evenly.
         */
        int[] colors = {
            0xFFE5BD7D,0xFFFAAA64,
            0xFFFFFFFF, 0xFF6AE2FD,
            0xFF8CD0E5, 0xFFA3CBCB,
            0xFFBDC7B3, 0xFFD1C299,
            0xFFE5BD7D,
        };
        float[] positions = {0,1f/8,2f/8,3f/8,4f/8,5f/8,6f/8,7f/8,1};
        mSweepGradient = new SweepGradient(mCenter, mCenter, colors , positions);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        /*****************   变色弧形部分  ************************/
        // draw arc 設置空心邊框的寬度
        // Set the width for stroking. Pass 0 to stroke in hairline mode. Hairlines always draws a single pixel independent of the canva's matrix.
        mArcPaint.setStrokeWidth(mGapWidth);
        int gapDegree = getDegree();
        // 绘制梯度渐变
        // Set or clear the shader object.
        mArcPaint.setShader(mSweepGradient);
        //画渐变色弧形
        // Draw the specified arc, which will be scaled to fit inside the specified oval.
        // If the start angle is negative or >= 360, the start angle is treated as start angle modulo 360.
        // If the sweep angle is >= 360, then the oval is drawn completely. Note that this differs slightly from SkPath::arcTo, which treats the sweep angle modulo 360. If the sweep angle is negative, the sweep angle is treated as sweep angle modulo 360
        // The arc is drawn clockwise. An angle of 0 degrees correspond to the geometric angle of 0 degrees (3 o'clock on a watch.)
        // Parameters
        //    oval            The bounds of oval used to define the shape and size of the arc
        //    startAngle    Starting angle (in degrees) where the arc begins
        //    sweepAngle    Sweep angle (in degrees) measured clockwise
        //    useCenter        If true, include the center of the oval in the arc, and close it if it is being stroked. This will draw a wedge
        //    paint            The paint used to draw the arc
        canvas.drawArc(mArcRect, -225, gapDegree + 225, false, mArcPaint);

        /*****************   白色弧形部分  ************************/
        mArcPaint.setShader(null);
        mArcPaint.setColor(Color.WHITE);

        //画渐变色弧形
        canvas.drawArc(mArcRect, gapDegree, 45 - gapDegree, false, mArcPaint);

        // draw line
        /*****************   画线部分  ************************/
        mLinePaint.setStrokeWidth(mMinSize*1.5f);
        // 将圆等分成120份,每份占360度的3度
        for(int i = 0; i<120; i++){
            // (75-45)*3 = 30*3 = 90,不绘直线部分占90度,正好符合空白区
            if(i<=45 || i >= 75){
                float top = mCenter-mInnerRadius-mGapWidth;
                // 2度分成15格
                if(i%15 == 0){
                    top = top - 20*mMinSize;
                }
                // 绘制垂直线
                canvas.drawLine(mCenter, mCenter - mInnerRadius, mCenter, top, mLinePaint);
            }
            /**
             * Preconcat the current matrix with the specified rotation.
             *
             * Parameters
             * degrees    The amount to rotate, in degrees
             * px    The x-coord for the pivot point (unchanged by the rotation)
             * py    The y-coord for the pivot point (unchanged by the rotation)
             *
             * 坐标系旋转3度,不是已经绘制的图形旋转3度
             */
            canvas.rotate(3,mCenter,mCenter);
        }

        // draw text
        /*****************   弧形外部显示温度度数文字 部分  ************************/
        mTextPaint.setTextSize(mMinSize*30);
        mTextPaint.setTextAlign(Paint.Align.CENTER);
        for(int i = 16; i<29; i+=2){
            /**
             * 计算文字在圆弧边缘的位置,用到三角函数计算。
             */
            float r = mInnerRadius+mGapWidth + 40*mMinSize;
            float x = (float) (mCenter + r*Math.cos((26-i)/2*Math.PI/4));
            float y = (float) (mCenter - r*Math.sin((26-i)/2*Math.PI/4));
            canvas.drawText(""+i, x, y - ((mTextPaint.descent() + mTextPaint.ascent()) / 2), mTextPaint);
        }
    }

    private int getDegree(){
        checkTemperature(mTemperature);
        return -225 + (int)((mTemperature-16)/12*90+0.5f)*3;
    }
    /*****************   用来控制事件的三个方法  ************************/
    private void checkTemperature(float t){
        if(t<16 || t > 28){
            throw new RuntimeException("Temperature out of range");
        }
    }

    public void setTemperature(float t){
        checkTemperature(t);
        mTemperature = t;
        // To force a view to draw, call invalidate().
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 获取触摸位置
        float x = event.getX();
        float y = event.getY();

        // 计算触摸点到中心点的距离,判断该点是否在圆弧之内
        double distance = Math.sqrt((x - mCenter) * (x - mCenter) + (y - mCenter) * (y - mCenter));
        if(distance < mInnerRadius || distance > mInnerRadius + mGapWidth){
            return false;
        }
        // 判断是否在空白区
        double degree = Math.atan2(-(y-mCenter),x-mCenter);
        if(-3*Math.PI/4<degree && degree < -Math.PI/4){
            return false;
        }
        // 计算角度,并转换为对应的温度,设置当前温度,设置温度之后会自动对View进行重绘
        if(degree < -3*Math.PI/4){
            degree = degree + 2*Math.PI;
        }
        float t = (float) (26 - degree*8/Math.PI);
        setTemperature(t);

        return true;
    }
    /*****************   为了获得mMinSize  ************************/
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int desiredWidth = Integer.MAX_VALUE;

        /**
         * Extracts the mode from the supplied measure specification.
         *
         * Parameters
         *     measureSpec    the measure specification to extract the mode from
         * Returns
         *     UNSPECIFIED, AT_MOST or EXACTLY
         */
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width;
        int height;

        //Measure Width
        if (widthMode == MeasureSpec.EXACTLY) {
            //Must be this size
            width = widthSize;
            //Toast.makeText(getContext(), "MeasureSpec.EXACTLY", 0).show();
        } else if (widthMode == MeasureSpec.AT_MOST) {
            width = Math.min(desiredWidth, widthSize);
            //Toast.makeText(getContext(), "MeasureSpec.AT_MOST"+desiredWidth+" "+widthSize, 0).show();
        } else {
            //Be whatever you want
            width = desiredWidth;
            //Toast.makeText(getContext(), "MeasureSpec.UNSPECIFIED", 0).show();
        }
        mMinSize = width/600f;

        int size = width;
        initSize();
        //Measure Height
        if (heightMode == MeasureSpec.EXACTLY) {
            //Must be this size
            height = heightSize;
        } else if (heightMode == View.MeasureSpec.AT_MOST) {
            //Can't be bigger than...
            height = Math.min(size, heightSize);
        } else {
            //Be whatever you want
            height = size;
        }

        //MUST CALL THIS
        /**
         * This method must be called by onMeasure(int, int) to store the measured width and measured height. Failing to do so will trigger an exception at measurement time.
         *
         * Parameters
         *     measuredWidth    The measured width of this view. May be a complex bit mask as defined by MEASURED_SIZE_MASK and MEASURED_STATE_TOO_SMALL.
         *     measuredHeight    The measured height of this view. May be a complex bit mask as defined by MEASURED_SIZE_MASK and MEASURED_STATE_TOO_SMALL.
         */
        setMeasuredDimension(width, height);
    }

}

 

时间: 2024-10-25 06:28:37

Android custom View AirConditionerView hacking的相关文章

Android: Custom View和include标签的区别

Custom View, 使用的时候是这样的: <com.example.home.alltest.view.MyCustomView android:id="@+id/customView" android:layout_width="match_parent" android:layout_height="wrap_content"> </com.example.home.alltest.view.MyCustomView&

我的Android进阶之旅------&amp;gt;Android自定义View实现带数字的进度条(NumberProgressBar)

今天在Github上面看到一个来自于 daimajia所写的关于Android自定义View实现带数字的进度条(NumberProgressBar)的精彩案例,在这里分享给大家一起来学习学习!同时感谢daimajia的开源奉献! 第一步.效果展示 图1.蓝色的进度条 图2.红色的进度条 图3.多条颜色不同的进度条 图4.多条颜色不同的进度条 版权声明:本文为[欧阳鹏]原创文章,欢迎转载,转载请注明出处! [http://blog.csdn.net/ouyang_peng/article/deta

Android自定义VIew实现卫星菜单效果浅析_Android

 一 概述: 最近一直致力于Android自定义VIew的学习,主要在看<android群英传>,还有CSDN博客鸿洋大神和wing大神的一些文章,写的很详细,自己心血来潮,学着写了个实现了类似卫星效果的一个自定义的View,分享到博客上,望各位指点一二.写的比较粗糙,见谅.(因为是在Linux系统下写的,效果图我直接用手机拍的,难看,大家讲究下就看个效果,勿喷). 先来看个效果图,有点不忍直视: 自定义VIew准备: (1)创建继承自View的类; (2)重写构造函数; (3)定义属性. (

Android自定义View实现带数字的进度条实例代码_Android

第一步.效果展示 图1.蓝色的进度条 图2.红色的进度条 图3.多条颜色不同的进度条 图4.多条颜色不同的进度条 第二步.自定义ProgressBar实现带数字的进度条 0.项目结构 如上图所示:library项目为自定义的带数字的进度条NumberProgressBar的具体实现,demo项目为示例项目以工程依赖的方式引用library项目,然后使用自定义的带数字的进度条NumberProgressBar来做展示   如上图所示:自定义的带数字的进度条的library项目的结构图   如上图所

Android 自定义View步骤_Android

例子如下:Android 自定义View 密码框 例子 1 良好的自定义View 易用,标准,开放. 一个设计良好的自定义view和其他设计良好的类很像.封装了某个具有易用性接口的功能组合,这些功能能够有效地使用CPU和内存,并且十分开放的.但是,除了开始一个设计良好的类之外,一个自定义view应该: l 符合安卓标准 l 提供能够在Android XML布局中工作的自定义样式属性 l 发送可访问的事件 l 与多个Android平台兼容. Android框架提供了一套基本的类和XML标签来帮您创

从源码解析Android中View的容器ViewGroup_Android

 这回我们是深入到ViewGroup内部\,了解ViewGroup的工作,同时会阐述更多有关于View的相关知识.以便为以后能灵活的使用自定义空间打更近一步的基础.希望有志同道合的朋友一起来探讨,深入Android内部,深入理解Android. 一.ViewGroup是什么?       一个ViewGroup是一个可以包含子View的容器,是布局文件和View容器的基类.在这个类里定义了ViewGroup.LayoutParams类,这个类是布局参数的子类.        其实ViewGrou

Android 自定义View时使用TypedArray配置样式属性详细介绍_Android

 Android 自定义View时使用TypedArray配置样式属性详细介绍       在自定义view时为了提高复用性和扩展性,可以为自定义的view添加样式属性的配置,比如自定义图片资源.文字大小.控件属性等,就这需要用到TypedArray类,下面以一个自定义的可点击扩展和收缩的TextView为例记录下这个类的简单使用. 先上效果图: 点击以后为 再贴代码: 1.自定义view类: /** * @title ExpandTextView * @description 可扩展TextV

Android自定义view制作绚丽的验证码_Android

废话不多说了,先给大家展示下自定义view效果图,如果大家觉得还不错的话,请继续往下阅读. 怎么样,这种验证码是不是很常见呢,下面我们就自己动手实现这种效果,自己动手,丰衣足食,哈哈~ 一. 自定义view的步骤 自定义view一直被认为android进阶通向高手的必经之路,其实自定义view好简单,自定义view真正难的是如何绘制出高难度的图形,这需要有好的数学功底(后悔没有好好学数学了~),因为绘制图形经常要计算坐标点及类似的几何变换等等.自定义view通常只需要以下几个步骤: 写一个类继承

Android自定义View实现验证码_Android

本文章是基于鸿洋的Android 自定义View (一) 的一些扩展,以及对Android自定义View构造函数详解里面内容的一些转载. 首先我们定义一个declare-styleable标签declare-styleable标签的作用是给自定义控件添加自定义属性用的例如这样 (我们定义了文字的颜色,大小,长度,跟背景的颜色) <declare-styleable name="CustomTitleView"> <attr name="titleColor&