Android(安卓)自定义view画圆
16lz
2021-12-04
今天自定义view画圆,使用到的就是Android也给我们提供了这两样东西:Paint和Canvas,由于在代码中都有对使用方法的介绍 我也不多说,来看自定义View的代码:
package com.haiwei.customview;import android.annotation.SuppressLint;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.view.Display;import android.view.View;import android.view.WindowManager;public class CustomViews extends View implements Runnable {private Paint mPaint;private Context mContext;private int screenWidth;private int screenHeight;private int radial = 50;public CustomViews(Context context) {super(context, null);init();}public CustomViews(Context context, AttributeSet attrs) {super(context, attrs);mContext = context;init();}/** * 由于onDraw()方法会不停的绘制 所以需要定义一个初始化画笔方法 避免导致不停创建造成内存消耗过大 */private void init() {mPaint = new Paint();// 设置画笔为抗锯齿mPaint.setAntiAlias(true);// 设置颜色为红色mPaint.setColor(Color.RED);/** * 画笔样式分三种: 1.Paint.Style.STROKE:描边 2.Paint.Style.FILL_AND_STROKE:描边并填充 * 3.Paint.Style.FILL:填充 */mPaint.setStyle(Paint.Style.STROKE);/** * 设置描边的粗细,单位:像素px 注意:当setStrokeWidth(0)的时候描边宽度并不为0而是只占一个像素 */mPaint.setStrokeWidth(20);/** * 获取屏幕的宽高 */WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);Display display = wm.getDefaultDisplay();screenWidth = display.getWidth();screenHeight = display.getHeight();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);/** * 绘制圆环drawCircle的前两个参数表示圆心的XY坐标, 这里我们用到了一个工具类获取屏幕尺寸以便将其圆心设置在屏幕中心位置, * 第三个参数是圆的半径,第四个参数则为我们的画笔 * */canvas.drawCircle(screenWidth / 2, screenHeight / 2, radial, mPaint);}@Overridepublic void run() {/** * 使用while循环不断的刷新view的半径 * 当半径小于100每次增加10 invalidate()重绘view会报错 * android.view.ViewRootImpl$CalledFromWrongThreadException 是非主线程更新UI * Android给提供postInvalidate();快捷方法来重绘view * 现在明白了invalidate和postInvalidate的小区别了吧 */ while (true) {if (radial <= 170) {radial += 20;postInvalidate();}else{radial = 50;}try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}}}}
在看我们在XML布局文件中是如果实现的:
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent">
在Activity里面为控件开个多线程即可:
package com.haiwei.customview;import android.app.Activity;import android.os.Bundle;public class MainActivity extends Activity {private CustomViews mCustomView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mCustomView = (CustomViews) findViewById(R.id.cv);new Thread(mCustomView).start();}}
在看我们最后实现的效果吧,以后还会继续写博客的哦,希望大家多多支持。。。
更多相关文章
- Android(安卓)关于获取摄像头帧数据
- android学习轨迹之二:Android权限标签uses-permission的书写位置
- 华为手机Android(安卓)Studio开发不显示Logcat解决办法
- Android(安卓)Studio 修改 Logcat 颜色
- Android(安卓)设置没有 actionBar的 样式
- Android中ListView中Item的设置
- Android(安卓)Toolbar
- Android(安卓)屏幕设置
- Android中各种形状