生活随笔
收集整理的這篇文章主要介紹了
安卓自定义View画钟实现转动
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.自定義View畫鐘實現轉動
這個和畫圓差不多,不過只是價格分針,并實現其轉動,要加一個線程。代碼如下:
Java類中的代碼
package com.example.ll.canvas;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.logging.Handler;
/*** Created by ll on 2018/3/30.*/public class CircleView extends View {private Paint paint =
new Paint();
private int sec;
private android.os.Handler handler =
new android.os.Handler() {
@Overridepublic void handleMessage(Message msg) {
super.handleMessage(msg);invalidate();}};
public CircleView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);}
@Overrideprotected void onDraw(Canvas canvas) {
super.onDraw(canvas);paint.setColor(Color.BLUE);paint.setAntiAlias(
true);paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(getWidth() /
2, getHeight() /
2, getHeight() /
4, paint);canvas.drawCircle(getWidth() /
2, getHeight() /
2, getHeight() /
80, paint);
for (
int i =
1; i <=
12; i++) {canvas.save();canvas.rotate(
360 /
12 * i, getWidth() /
2, getHeight() /
2);paint.setTextSize(
40);canvas.drawText(String.valueOf(i), getWidth() /
2 -
15, getHeight() /
2 - getHeight() /
4 +
60, paint);canvas.drawLine(getWidth() /
2, getHeight() /
2 - getHeight() /
4, getWidth() /
2, getHeight() /
2 - getHeight() /
4 +
30, paint);canvas.restore();}canvas.save();canvas.rotate(
6 * sec, getWidth() /
2, getHeight() /
2);canvas.drawLine(getWidth() /
2, getHeight() /
2, getWidth() /
2, getHeight() /
2 - getHeight() /
4 +
100, paint);canvas.restore();}
@Overridepublic boolean onTouchEvent(MotionEvent event) {
new Thread(
new Runnable() {
@Overridepublic void run() {
while (
true) {sec++;
try {Thread.sleep(
1000);}
catch (InterruptedException e) {e.printStackTrace();}handler.sendEmptyMessage(sec);}}}).start();
return super.onTouchEvent(event);}
}
xml中的代碼
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.example.ll.canvas.CircleActivity"><com.example.ll.canvas.CircleView
android:layout_width="match_parent"android:layout_height="match_parent" /></android.support.constraint.ConstraintLayout>
效果圖如下:
總結
以上是生活随笔為你收集整理的安卓自定义View画钟实现转动的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。