├── .gitignore ├── .idea ├── .name ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── gradle.xml ├── misc.xml ├── runConfigurations.xml └── vcs.xml ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── caobo │ │ └── customizeview │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── caobo │ │ │ └── customizeview │ │ │ ├── CustomizeView.kt │ │ │ └── MainActivity.kt │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── caobo │ └── customizeview │ └── ExampleUnitTest.kt ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── readme.md └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | CustomizeView -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 9 | 10 | 11 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | xmlns:android 20 | 21 | ^$ 22 | 23 | 24 | 25 |
26 |
27 | 28 | 29 | 30 | xmlns:.* 31 | 32 | ^$ 33 | 34 | 35 | BY_NAME 36 | 37 |
38 |
39 | 40 | 41 | 42 | .*:id 43 | 44 | http://schemas.android.com/apk/res/android 45 | 46 | 47 | 48 |
49 |
50 | 51 | 52 | 53 | .*:name 54 | 55 | http://schemas.android.com/apk/res/android 56 | 57 | 58 | 59 |
60 |
61 | 62 | 63 | 64 | name 65 | 66 | ^$ 67 | 68 | 69 | 70 |
71 |
72 | 73 | 74 | 75 | style 76 | 77 | ^$ 78 | 79 | 80 | 81 |
82 |
83 | 84 | 85 | 86 | .* 87 | 88 | ^$ 89 | 90 | 91 | BY_NAME 92 | 93 |
94 |
95 | 96 | 97 | 98 | .* 99 | 100 | http://schemas.android.com/apk/res/android 101 | 102 | 103 | ANDROID_ATTRIBUTE_ORDER 104 | 105 |
106 |
107 | 108 | 109 | 110 | .* 111 | 112 | .* 113 | 114 | 115 | BY_NAME 116 | 117 |
118 |
119 |
120 |
121 | 122 | 124 |
125 |
-------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 18 | 19 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | apply plugin: 'kotlin-android' 4 | 5 | apply plugin: 'kotlin-android-extensions' 6 | 7 | android { 8 | compileSdkVersion 29 9 | buildToolsVersion "29.0.2" 10 | defaultConfig { 11 | applicationId "com.caobo.customizeview" 12 | minSdkVersion 26 13 | targetSdkVersion 29 14 | versionCode 1 15 | versionName "1.0" 16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 17 | } 18 | buildTypes { 19 | release { 20 | minifyEnabled false 21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 22 | } 23 | } 24 | } 25 | 26 | dependencies { 27 | implementation fileTree(dir: 'libs', include: ['*.jar']) 28 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 29 | implementation 'androidx.appcompat:appcompat:1.1.0' 30 | implementation 'androidx.core:core-ktx:1.0.2' 31 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 32 | testImplementation 'junit:junit:4.12' 33 | androidTestImplementation 'androidx.test.ext:junit:1.1.1' 34 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 35 | } 36 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/caobo/customizeview/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.caobo.customizeview 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.caobo.customizeview", appContext.packageName) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/src/main/java/com/caobo/customizeview/CustomizeView.kt: -------------------------------------------------------------------------------- 1 | package com.caobo.customizeview 2 | 3 | import android.content.Context 4 | import android.graphics.* 5 | import android.util.AttributeSet 6 | import android.view.View 7 | import java.util.* 8 | import kotlin.math.* 9 | 10 | /** 11 | * Created by jaynm 12 | * 关注公众号:码农专栏 获取更多学习资料 13 | * on 2020-05-26. 14 | */ 15 | class CustomizeView @JvmOverloads constructor( 16 | context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 17 | ) : View(context, attrs, defStyleAttr) { 18 | 19 | // 时针宽度 20 | private val mHourPointWidth = 15f 21 | 22 | // 分针宽度 23 | private val mMinutePointWidth = 10f 24 | 25 | // 秒针宽度 26 | private val mSecondPointWidth = 4f 27 | 28 | // 指针矩形弧度 29 | private val mPointRange = 20F 30 | 31 | // 刻度与数字间距 32 | private val mNumberSpace = 10f 33 | 34 | // 表盘宽度 35 | private val mCircleWidth = 4.0F 36 | 37 | // 设置表盘整点刻度尺寸 38 | private val scaleMax = 50 39 | 40 | // 设置表盘非整点刻度尺寸 41 | private val scaleMin = 25 42 | 43 | // View宽度 44 | private var mWidth = 0 45 | 46 | // View高度 47 | private var mHeight = 0 48 | 49 | // 圆半径,默认200像素 50 | private var radius = 300.0F 51 | 52 | // 画笔 53 | private val mPaint: Paint by lazy { 54 | Paint() 55 | } 56 | private val mRect: Rect by lazy { 57 | Rect() 58 | } 59 | 60 | 61 | // 初始化画笔属性 62 | init { 63 | mPaint.textSize = 35F 64 | mPaint.typeface = Typeface.DEFAULT_BOLD 65 | mPaint.isAntiAlias = true 66 | 67 | // // 设置圆心X轴位置 68 | // val centerX: Float = width / 2F 69 | // // 设置圆心Y轴位置 70 | // val centerY: Float = height / 2F 71 | // // 设置圆半径,默认设置为1/4屏幕宽度,可添加为自定义属性 72 | // val radius: Float = width / 4F 73 | } 74 | 75 | 76 | override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { 77 | super.onMeasure(widthMeasureSpec, heightMeasureSpec) 78 | 79 | mWidth = onMeasuredSpec(widthMeasureSpec) + (mCircleWidth * 2).toInt() 80 | mHeight = onMeasuredSpec(heightMeasureSpec) + (mCircleWidth * 2).toInt() 81 | 82 | radius = (mWidth - mCircleWidth * 2) / 2 83 | setMeasuredDimension(mWidth, mHeight) 84 | } 85 | 86 | private fun onMeasuredSpec(measureSpec: Int): Int { 87 | 88 | var specViewSize = 0 89 | val specMode = MeasureSpec.getMode(measureSpec) 90 | val specSize = MeasureSpec.getSize(measureSpec) 91 | 92 | when (specMode) { 93 | MeasureSpec.EXACTLY -> { 94 | specViewSize = specSize 95 | } 96 | MeasureSpec.AT_MOST -> { 97 | // 计算半径以宽高最小值为准 98 | specViewSize = min((radius * 2).toInt(), specSize) 99 | } 100 | } 101 | return specViewSize 102 | } 103 | 104 | override fun onDraw(canvas: Canvas) { 105 | super.onDraw(canvas) 106 | 107 | // 设置圆心X轴位置 108 | val centerX: Float = (mWidth / 2).toFloat() 109 | // 设置圆心Y轴位置 110 | val centerY: Float = (mHeight / 2).toFloat() 111 | 112 | canvas.translate(centerX, centerY) 113 | 114 | /** 第一步:绘制最外层的圆 **/ 115 | drawClock(canvas) 116 | 117 | /** 第二步:表盘一共60个刻度,1到12点整数属于长刻度,其余属于短刻度 **/ 118 | drawClockScale(canvas) 119 | 120 | /** 第三步:绘制指针 **/ 121 | drawPointer(canvas) 122 | 123 | postInvalidateDelayed(1000) 124 | 125 | } 126 | 127 | /** 128 | * 绘制表盘 129 | */ 130 | private fun drawClock(canvas: Canvas) { 131 | 132 | // 设置外层圆画笔宽度 133 | mPaint.strokeWidth = mCircleWidth 134 | // 设置画笔颜色 135 | mPaint.color = Color.BLACK 136 | // 设置画笔空心风格 137 | mPaint.style = Paint.Style.STROKE 138 | // 绘制圆方法 139 | canvas.drawCircle(0F, 0F, radius, mPaint) 140 | } 141 | 142 | /** 143 | * 绘制表盘刻度 144 | */ 145 | private fun drawClockScale(canvas: Canvas) { 146 | for (index in 1..60) { 147 | // 刻度绘制以12点钟为准,每次将表盘旋转6°,后续绘制都以12点钟为基准绘制 148 | canvas.rotate(6F, 0F, 0F) 149 | // 绘制长刻度线 150 | if (index % 5 == 0) { 151 | // 设置长刻度画笔宽度 152 | mPaint.strokeWidth = 4.0F 153 | // 绘制刻度线 154 | canvas.drawLine(0F, -radius, 0F, -radius + scaleMax, mPaint) 155 | /** 绘制文本 **/ 156 | canvas.save() 157 | // 设置画笔宽度 158 | mPaint.strokeWidth = 1.0F 159 | // 设置画笔实心风格 160 | mPaint.style = Paint.Style.FILL 161 | mPaint.getTextBounds( 162 | (index / 5).toString(), 163 | 0, 164 | (index / 5).toString().length, 165 | mRect 166 | ) 167 | canvas.translate(0F, -radius + mNumberSpace + scaleMax + (mRect.height() / 2)) 168 | canvas.rotate((index * -6).toFloat()) 169 | canvas.drawText( 170 | (index / 5).toString(), -mRect.width() / 2.toFloat(), 171 | mRect.height().toFloat() / 2, mPaint 172 | ) 173 | canvas.restore() 174 | } 175 | // 绘制短刻度线 176 | else { 177 | // 设置短刻度画笔宽度 178 | mPaint.strokeWidth = 2.0F 179 | canvas.drawLine(0F, -radius, 0F, -radius + scaleMin, mPaint) 180 | } 181 | } 182 | } 183 | 184 | /** 185 | * 绘制表盘数字 186 | */ 187 | private fun drawClockNumber(canvas: Canvas, centerX: Float, centerY: Float) { 188 | // var x = 0.0F // 数字x坐标 189 | // var y = 0.0F // 数字y坐标 190 | // // 设置画笔宽度 191 | // mPaint.strokeWidth = 1.0F 192 | // // 设置画笔实心风格 193 | // mPaint.style = Paint.Style.FILL 194 | // 195 | // // 数字距离表盘边界距离:半径-刻度线长度-数字距离刻度线间距 196 | // var tempSpace = radius - scaleMax - mNumberSpace 197 | // 198 | // // 遍历绘制表盘数字 199 | // for (num in 1..12) { 200 | // mPaint.getTextBounds((num).toString(), 0, (num).toString().length, mRect) 201 | // if (num == 1 || num == 2) { 202 | // x = 203 | // (centerX + tempSpace * sin(Math.toRadians(num * 30.0)) - mRect.width()).toFloat() 204 | // y = 205 | // (centerY - tempSpace * cos(Math.toRadians(num * 30.0)) + mRect.height()).toFloat() 206 | // } else if (num == 4 || num == 5) { 207 | // x = 208 | // (centerX + tempSpace * sin(Math.toRadians(num * 30.0)) - mRect.width()).toFloat() 209 | // y = (centerY - tempSpace * cos(Math.toRadians(num * 30.0))).toFloat() 210 | // } else if (num == 7 || num == 8) { 211 | // x = (centerX + tempSpace * sin(Math.toRadians(num * 30.0))).toFloat() 212 | // y = (centerY - tempSpace * cos(Math.toRadians(num * 30.0))).toFloat() 213 | // } else if (num == 10 || num == 11) { 214 | // x = (centerX + tempSpace * sin(Math.toRadians(num * 30.0))).toFloat() 215 | // y = 216 | // (centerY - tempSpace * cos(Math.toRadians(num * 30.0)) + mRect.height()).toFloat() 217 | // } else if (num == 3) { 218 | // x = 219 | // (centerX + tempSpace * sin(Math.toRadians(num * 30.0)) - mRect.width()).toFloat() 220 | // y = 221 | // (centerY - tempSpace * cos(Math.toRadians(num * 30.0)) + mRect.height() / 2).toFloat() 222 | // } else if (num == 6) { 223 | // x = 224 | // (centerX + tempSpace * sin(Math.toRadians(num * 30.0)) - mRect.width() / 2).toFloat() 225 | // y = (centerY - tempSpace * cos(Math.toRadians(num * 30.0))).toFloat() 226 | // } else if (num == 9) { 227 | // x = (centerX + tempSpace * sin(Math.toRadians(num * 30.0))).toFloat() 228 | // y = 229 | // (centerY - tempSpace * cos(Math.toRadians(num * 30.0)) + mRect.height() / 2).toFloat() 230 | // } else if (num == 12) { 231 | // x = 232 | // (centerX + tempSpace * sin(Math.toRadians(num * 30.0)) - mRect.width() / 2).toFloat() 233 | // y = 234 | // (centerY - tempSpace * cos(Math.toRadians(num * 30.0)) + mRect.height()).toFloat() 235 | // } 236 | // 237 | // canvas.drawText(num.toString(), x, y, mPaint) 238 | // } 239 | } 240 | 241 | /** 242 | * 第四步:绘制指针 243 | */ 244 | private fun drawPointer(canvas: Canvas) { 245 | // 获取当前时间:时分秒 246 | val calendar = Calendar.getInstance() 247 | val hour = calendar[Calendar.HOUR] 248 | val minute = calendar[Calendar.MINUTE] 249 | val second = calendar[Calendar.SECOND] 250 | // 计算时分秒转过的角度 251 | val angleHour = (hour + minute.toFloat() / 60) * 360 / 12 252 | val angleMinute = (minute + second.toFloat() / 60) * 360 / 60 253 | val angleSecond = second * 360 / 60 254 | 255 | // 绘制时针 256 | canvas.save() 257 | // 旋转到时针的角度 258 | canvas.rotate(angleHour, 0F, 0F) 259 | val rectHour = RectF( 260 | -mHourPointWidth / 2, 261 | -radius / 2, 262 | mHourPointWidth / 2, 263 | radius / 6 264 | ) 265 | // 设置时针画笔属性 266 | mPaint.color = Color.BLUE 267 | mPaint.style = Paint.Style.STROKE 268 | mPaint.strokeWidth = mHourPointWidth 269 | canvas.drawRoundRect(rectHour, mPointRange, mPointRange, mPaint) 270 | canvas.restore() 271 | 272 | // 绘制分针 273 | canvas.save() 274 | // 旋转到分针的角度 275 | canvas.rotate(angleMinute, 0F, 0F) 276 | val rectMinute = RectF( 277 | -mMinutePointWidth / 2, 278 | -radius * 3.5f / 5, 279 | mMinutePointWidth / 2, 280 | radius / 6 281 | ) 282 | // 设置分针画笔属性 283 | mPaint.color = Color.BLACK 284 | mPaint.strokeWidth = mMinutePointWidth 285 | canvas.drawRoundRect(rectMinute, mPointRange, mPointRange, mPaint) 286 | canvas.restore() 287 | 288 | // 绘制秒针 289 | canvas.save() 290 | // 旋转到分针的角度 291 | canvas.rotate(angleSecond.toFloat(), 0F, 0F) 292 | val rectSecond = RectF( 293 | -mSecondPointWidth / 2, 294 | -radius + 10, 295 | mSecondPointWidth / 2, 296 | radius / 6 297 | ) 298 | // 设置秒针画笔属性 299 | mPaint.strokeWidth = mSecondPointWidth 300 | mPaint.color = Color.RED 301 | canvas.drawRoundRect(rectSecond, mPointRange, mPointRange, mPaint) 302 | canvas.restore() 303 | 304 | // 绘制原点 305 | mPaint.style = Paint.Style.FILL 306 | canvas.drawCircle( 307 | 0F, 308 | 0F, mSecondPointWidth * 4, mPaint 309 | ) 310 | } 311 | } 312 | 313 | -------------------------------------------------------------------------------- /app/src/main/java/com/caobo/customizeview/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.caobo.customizeview 2 | 3 | import androidx.appcompat.app.AppCompatActivity 4 | import android.os.Bundle 5 | 6 | class MainActivity : AppCompatActivity() { 7 | 8 | override fun onCreate(savedInstanceState: Bundle?) { 9 | super.onCreate(savedInstanceState) 10 | setContentView(R.layout.activity_main) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34 | 36 | 38 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 62 | 64 | 66 | 68 | 70 | 72 | 74 | 75 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JaynmBo/ClockCustomizeView/18eafb422ba1f32816d96ca32719d158b580175f/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JaynmBo/ClockCustomizeView/18eafb422ba1f32816d96ca32719d158b580175f/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JaynmBo/ClockCustomizeView/18eafb422ba1f32816d96ca32719d158b580175f/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JaynmBo/ClockCustomizeView/18eafb422ba1f32816d96ca32719d158b580175f/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JaynmBo/ClockCustomizeView/18eafb422ba1f32816d96ca32719d158b580175f/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JaynmBo/ClockCustomizeView/18eafb422ba1f32816d96ca32719d158b580175f/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JaynmBo/ClockCustomizeView/18eafb422ba1f32816d96ca32719d158b580175f/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JaynmBo/ClockCustomizeView/18eafb422ba1f32816d96ca32719d158b580175f/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JaynmBo/ClockCustomizeView/18eafb422ba1f32816d96ca32719d158b580175f/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JaynmBo/ClockCustomizeView/18eafb422ba1f32816d96ca32719d158b580175f/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | CustomizeView 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/caobo/customizeview/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.caobo.customizeview 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext.kotlin_version = '1.3.70' 5 | repositories { 6 | google() 7 | maven{url 'http://maven.aliyun.com/nexus/content/groups/public/'} 8 | // jcenter() 9 | 10 | } 11 | dependencies { 12 | classpath 'com.android.tools.build:gradle:3.5.3' 13 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 14 | // NOTE: Do not place your application dependencies here; they belong 15 | // in the individual module build.gradle files 16 | } 17 | } 18 | 19 | allprojects { 20 | repositories { 21 | google() 22 | // jcenter() 23 | maven{url 'http://maven.aliyun.com/nexus/content/groups/public/'} 24 | } 25 | } 26 | 27 | task clean(type: Delete) { 28 | delete rootProject.buildDir 29 | } 30 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | 19 | # AndroidX package structure to make it clearer which packages are bundled with the 20 | # Android operating system, and which are packaged with your app's APK 21 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 22 | android.useAndroidX=true 23 | # Automatically convert third-party libraries to use AndroidX 24 | android.enableJetifier=true 25 | 26 | # Kotlin code style for this project: "official" or "obsolete": 27 | kotlin.code.style=official 28 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JaynmBo/ClockCustomizeView/18eafb422ba1f32816d96ca32719d158b580175f/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue May 26 09:49:12 CST 2020 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ## 一、前言 2 | 3 | Android 自定义View是高级进阶不可或缺的内容,日常工作中,经常会遇到产品、UI设计出花里胡哨的界面。当系统自带的控件不能满足开发需求时,就只能自己动手撸一个效果。 4 | 5 | 本文就带自定义View初学者手动撸一个效果,通过自定义View实现钟表功能,**每行代码都有注释,保证易懂,看不懂你留言打我!!!** 6 | 7 | ## 二、实现效果 8 | 9 | ### 1、先看效果图 10 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200527170644942.gif#pic_center) 11 | 12 | 13 | ### 2、下载地址:[点击下载](https://github.com/jaynm888/ClockCustomizeView.git) 14 | ### 3、步骤分析 15 | 16 | 实现以上效果,主要分为四个步骤: 17 | 18 | 1. 绘制外层表盘 19 | 2. 绘制刻度线 20 | 3. 绘制刻度数字 21 | 4. 绘制指针 22 | 23 | ## 三、代码实现 24 | ### 1、绘制外层表盘 25 | 26 | 外层表盘就是一个空心圆,只要获取圆的x、y轴位置、圆的半径,使用Canvas.drawCircle()方法即可完成。 27 | 28 | ```kotlin 29 | /** 30 | * 绘制表盘 31 | */ 32 | private fun drawClock(canvas: Canvas, centerX: Float, centerY: Float) { 33 | 34 | // 设置外层圆画笔宽度 35 | mPaint.strokeWidth = mCircleWidth 36 | // 设置画笔颜色 37 | mPaint.color = Color.BLACK 38 | // 设置画笔空心风格 39 | mPaint.style = Paint.Style.STROKE 40 | // 绘制圆方法 41 | canvas.drawCircle(centerX, centerY, radius, mPaint) 42 | } 43 | ``` 44 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200527164305615.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2pheW5t,size_16,color_FFFFFF,t_70#pic_center) 45 | 46 | ### 2、绘制刻度线 47 | 48 | **绘制思路分析** 49 | 50 | 看到效果图上密密麻麻刻度线后,先不要着急上手,屡清楚绘制思路。绘制刻度线一定要结合Canvas几何变换思路完成,千万不要局限于效果图的表面(如果对Canvas相关API不熟悉的朋友,建议先了解下)。 51 | 52 | 1. 假设以12点钟为例,那么刻度线就是一条笔直的竖线,调用Canvas.drawLine()方法完成绘制。 53 | 2. 如果每绘制完成一个刻度,把表盘逆时针/顺时针旋转一定角度,将下次需要绘制刻度线的位置旋转到12点钟位置,那么每次绘制刻度线的startX、startY、stopX、stopY一致(一致仅代表所有长刻度一致,所有短刻度一致)。 54 | 3. 观察表盘共有60个刻度线(12长,48短),那么每次旋转角度**degrees=360/60** 55 | 56 | 听完以上分析,是否觉得绘制刻度线很简单,只要在60个刻度遍历判断长短,即可轻松出效果。 57 | 58 | ```kotlin 59 | /** 60 | * 绘制表盘刻度 61 | */ 62 | private fun drawClockScale(canvas: Canvas, centerX: Float, centerY: Float) { 63 | for (index in 1..60) { 64 | // 刻度绘制以12点钟为准,每次将表盘旋转6°,后续绘制都以12点钟为基准绘制 65 | canvas.rotate(6F, centerX, centerY) 66 | // 绘制长刻度线 67 | if (index % 5 == 0) { 68 | // 设置长刻度画笔宽度 69 | mPaint.strokeWidth = 4.0F 70 | // 绘制刻度线 71 | canvas.drawLine( 72 | centerX, 73 | centerY - radius, 74 | centerX, 75 | centerY - radius + scaleMax, 76 | mPaint 77 | ) 78 | } 79 | // 绘制短刻度线 80 | else { 81 | // 设置短刻度画笔宽度 82 | mPaint.strokeWidth = 2.0F 83 | canvas.drawLine( 84 | centerX, 85 | centerY - radius, 86 | centerX, 87 | centerY - radius + scaleMin, 88 | mPaint 89 | ) 90 | } 91 | } 92 | } 93 | ``` 94 | 95 | ### 3、绘制数字新方案 96 | 热心网友指导我绘制数字新方案,真的是高手如云阿。 97 | 98 | 首先将坐标位置(0,0)设置到圆心位置,这步是在绘制外层圆的时候,已经设置了。这样的好处是后期减少很多计算的步骤,新方案已经在代码中更改! 99 | 100 | ```kotlin 101 | canvas.translate(centerX, centerY) 102 | ``` 103 | 104 | 主要是通过canvas几何变换方式,先将圆点平移到12点钟位置,然后逆时针旋转数字对应的角度,然后开始绘制数字文本。这样的话,绘制数字文本就和绘制刻度线可以一并完成,使得代码清晰很多。 105 | 需要注意的是,记得在使用几何变换前后分别调用**canvas.restore()和canvas.restore()方法**。 106 | 107 | 其中相关坐标计算方式: 108 | 109 | >**1、平移 y 轴距离 = - 半径 + 刻度线长度 + 刻度与文本间距 + 文本高度 / 2** 110 | >(因为坐标原点在圆心,需要平移到12点钟位置,所以半径为负数) 111 | >**2、旋转角度 = - 6 * 数字大小** 112 | >**3、文本 x 轴距离 = 文本宽度 / 2 ;** 113 | >**4、文本 y 轴距离 = 文本高度 / 2 ;** 114 | 115 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200527164347315.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2pheW5t,size_16,color_FFFFFF,t_70#pic_center) 116 | 117 | 118 | 附上绘制刻度线和文本的完整代码: 119 | ```kotlin 120 | /** 121 | * 绘制表盘刻度线和数字文本 122 | */ 123 | private fun drawClockScale(canvas: Canvas) { 124 | for (index in 1..60) { 125 | // 刻度绘制以12点钟为准,每次将表盘旋转6°,后续绘制都以12点钟为基准绘制 126 | canvas.rotate(6F, 0F, 0F) 127 | // 绘制长刻度线 128 | if (index % 5 == 0) { 129 | // 设置长刻度画笔宽度 130 | mPaint.strokeWidth = 4.0F 131 | // 绘制刻度线 132 | canvas.drawLine(0F, -radius, 0F, -radius + scaleMax, mPaint) 133 | /** 绘制文本 **/ 134 | canvas.save() 135 | // 设置画笔宽度 136 | mPaint.strokeWidth = 1.0F 137 | // 设置画笔实心风格 138 | mPaint.style = Paint.Style.FILL 139 | mPaint.getTextBounds( 140 | (index / 5).toString(), 141 | 0, 142 | (index / 5).toString().length, 143 | mRect 144 | ) 145 | canvas.translate(0F, -radius + mNumberSpace + scaleMax + (mRect.height() / 2)) 146 | canvas.rotate((index * -6).toFloat()) 147 | canvas.drawText( 148 | (index / 5).toString(), -mRect.width() / 2.toFloat(), 149 | mRect.height().toFloat() / 2, mPaint 150 | ) 151 | canvas.restore() 152 | } 153 | // 绘制短刻度线 154 | else { 155 | // 设置短刻度画笔宽度 156 | mPaint.strokeWidth = 2.0F 157 | canvas.drawLine(0F, -radius, 0F, -radius + scaleMin, mPaint) 158 | } 159 | } 160 | } 161 | ``` 162 | 163 | ### 4、绘制指针 164 | 165 | 指针绘制具体分以下步骤: 166 | 167 | 1. 首先获取当前时间 168 | 2. 根据当前时间计算指针旋转过的角度 169 | 3. 利用Canvas.rotate()旋转画布 170 | 4. 使用Canvas.drawRoundRect()绘制指针矩形 171 | 5. 绘制圆点 172 | 173 | ```kotlin 174 | /** 175 | * 第四步:绘制指针 176 | */ 177 | private fun drawPointer(canvas: Canvas, centerX: Float, centerY: Float) { 178 | // 获取当前时间:时分秒 179 | val calendar = Calendar.getInstance() 180 | val hour = calendar[Calendar.HOUR] 181 | val minute = calendar[Calendar.MINUTE] 182 | val second = calendar[Calendar.SECOND] 183 | // 计算时分秒转过的角度 184 | val angleHour = (hour + minute.toFloat() / 60) * 360 / 12 185 | val angleMinute = (minute + second.toFloat() / 60) * 360 / 60 186 | val angleSecond = second * 360 / 60 187 | 188 | // 绘制时针 189 | canvas.save() 190 | // 旋转到时针的角度 191 | canvas.rotate(angleHour, centerX, centerY) 192 | val rectHour = RectF( 193 | centerX - mHourPointWidth / 2, 194 | centerY - radius / 2, 195 | centerX + mHourPointWidth / 2, 196 | centerY + radius / 6 197 | ) 198 | // 设置时针画笔属性 199 | mPaint.color = Color.BLUE 200 | mPaint.style = Paint.Style.STROKE 201 | mPaint.strokeWidth = mHourPointWidth 202 | canvas.drawRoundRect(rectHour, mPointRange, mPointRange, mPaint) 203 | canvas.restore() 204 | 205 | // 绘制分针 206 | canvas.save() 207 | // 旋转到分针的角度 208 | canvas.rotate(angleMinute, centerX, centerY) 209 | val rectMinute = RectF( 210 | centerX - mMinutePointWidth / 2, 211 | centerY - radius * 3.5f / 5, 212 | centerX + mMinutePointWidth / 2, 213 | centerY + radius / 6 214 | ) 215 | // 设置分针画笔属性 216 | mPaint.color = Color.BLACK 217 | mPaint.strokeWidth = mMinutePointWidth 218 | canvas.drawRoundRect(rectMinute, mPointRange, mPointRange, mPaint) 219 | canvas.restore() 220 | 221 | // 绘制秒针 222 | canvas.save() 223 | // 旋转到分针的角度 224 | canvas.rotate(angleSecond.toFloat(), centerX, centerY) 225 | val rectSecond = RectF( 226 | centerX - mSecondPointWidth / 2, 227 | centerY - radius + 10, 228 | centerX + mSecondPointWidth / 2, 229 | centerY + radius / 6 230 | ) 231 | // 设置秒针画笔属性 232 | mPaint.strokeWidth = mSecondPointWidth 233 | mPaint.color = Color.RED 234 | canvas.drawRoundRect(rectSecond, mPointRange, mPointRange, mPaint) 235 | canvas.restore() 236 | 237 | // 绘制原点 238 | mPaint.style = Paint.Style.FILL 239 | canvas.drawCircle( 240 | (centerX).toFloat(), 241 | (centerY).toFloat(), mSecondPointWidth * 4, mPaint 242 | ) 243 | } 244 | ``` 245 | 以上就已经完成表盘指针绘制工作,效果图如下: 246 | 247 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200527164358620.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2pheW5t,size_16,color_FFFFFF,t_70#pic_center) 248 | ### 6、onMeasure测量View宽高 249 | 250 | MeasureSpecMode有三个属性:**EXACTLY、AT_MOST、UNSPECIFIED** 251 | 252 | 根据View在xml设置宽高类型不同会触发相应的方法,这里对onMeasure()测量不做具体讲解,如果对自定义View测量宽高onMeasure()方法不熟悉的,请自己补习。onMeasure()方法也是自定义View学习过程中非常重要的一个环节! 253 | 254 | ```kotlin 255 | override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { 256 | super.onMeasure(widthMeasureSpec, heightMeasureSpec) 257 | // 根据表盘半径 + 表盘圆环宽度计算View宽度和高度 258 | mWidth = onMeasuredSpec(widthMeasureSpec) + (mCircleWidth * 2).toInt() 259 | mHeight = onMeasuredSpec(heightMeasureSpec) + (mCircleWidth * 2).toInt() 260 | // 计算最终View表盘的半径 261 | radius = (mWidth - mCircleWidth * 2) / 2 262 | // 设置View最终宽高 263 | setMeasuredDimension(mWidth, mHeight) 264 | } 265 | ``` 266 | 267 | ```kotlin 268 | private fun onMeasuredSpec(measureSpec: Int): Int { 269 | // 临时值,用于计算后返回 270 | var specViewSize = 0 271 | val specMode = MeasureSpec.getMode(measureSpec) 272 | val specSize = MeasureSpec.getSize(measureSpec) 273 | 274 | when (specMode) { 275 | MeasureSpec.EXACTLY -> { 276 | // 一般为固定尺寸或者match_parent 277 | specViewSize = specSize 278 | } 279 | MeasureSpec.AT_MOST -> { 280 | // 计算半径以宽高最小值为准 281 | specViewSize = min((radius * 2).toInt(), specSize) 282 | } 283 | } 284 | return specViewSize 285 | } 286 | ``` 287 | 288 | 289 | 到此为止,如果想让表盘和指针动起来,还需要在onDraw()方法里调用**postInvalidateDelayed(1000)方法,或者启动一个线程**,使每秒钟刷新重绘一次布局,这样就可以让指针实时更新时间。最后贴上onDraw()方法里面的代码: 290 | 291 | ```kotlin 292 | override fun onDraw(canvas: Canvas) { 293 | super.onDraw(canvas) 294 | 295 | // 设置圆心X轴位置 296 | val centerX: Float = (mWidth / 2).toFloat() 297 | // 设置圆心Y轴位置 298 | val centerY: Float = (mHeight / 2).toFloat() 299 | 300 | /** 第一步:绘制最外层的圆 **/ 301 | drawClock(canvas, centerX, centerY) 302 | /** 第二步:表盘一共60个刻度,1到12点整数属于长刻度,其余属于短刻度 **/ 303 | drawClockScale(canvas, centerX, centerY) 304 | /** 第三步:绘制表盘数字 **/ 305 | drawClockNumber(canvas, centerX, centerY) 306 | /** 第四步:绘制指针 **/ 307 | drawPointer(canvas, centerX, centerY) 308 | // 刷新表盘指针 309 | postInvalidateDelayed(1000) 310 | } 311 | ``` 312 | 313 | ## 总结 314 | 315 | 自定view在Android开发过程中应用极其广泛,为了更好的掌握,建议从自定义View绘制流程、Canvas、Paint、Path、onLayout()、onMeasure()、onDraw()系统化学习,然后上手多做练习,这样势必会对自定义View有很好的提升! 316 | 317 | 看完文章,是不是觉得这个效果其实也很简单,案例中相关属性可以使用自定义属性,因为练习案例,所以这里在View中直接写死了,感兴趣的朋友可以使用自定义属性尝试实现。这个案例基本上将自定义View中Canvas、Paint常见的API方法以及onMeasure()测量方法都应用到了,算是一个上手练习自定义View的好案例,希望看完文章对你学习有所帮助! 318 | 319 | 前文说过,保证每个自定义View初学者都能看懂,因为每行代码都会添加注释,如果没看懂的留言打我!!! 320 | 321 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200527164416919.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2pheW5t,size_16,color_FFFFFF,t_70#pic_center) -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | rootProject.name='CustomizeView' 3 | --------------------------------------------------------------------------------