在Android屏幕中绘制虚线,最通用的是自定义控件DashedLine,再将自定义控件放入xml布局中
运行截图:
程序结构
package com.example.asus.gary_042;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.DashPathEffect;import android.graphics.Paint;import android.graphics.Path;import android.graphics.PathEffect;import android.util.AttributeSet;import android.view.View;/*** Created by ASUS on /5/26.*/public class DashedLine extends View{public DashedLine(Context context,AttributeSet attrs) {super(context,attrs);}protected void onDraw(Canvas canvas){super.onDraw(canvas);Paint paint = new Paint();paint.setStyle(Paint.Style.STROKE);paint.setColor(Color.BLACK);Path path = new Path();path.moveTo(0,200);path.lineTo(1280,200);PathEffect effects = new DashPathEffect(new float[]{5,5,5,5},1);paint.setPathEffect(effects);canvas.drawPath(path,paint);}}
DashedLine
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.example.asus.gary_042.MainActivity"><com.example.asus.gary_042.DashedLineandroid:id="@+id/dashedLine"android:layout_width="match_parent"android:layout_height="match_parent" /></LinearLayout>
activity_main.xml
一、自定义控件DashedLine,使用这个控件能在屏幕中绘制一条虚线
protected void onDraw(Canvas canvas){super.onDraw(canvas);Paint paint = new Paint();//给path设置样式(效果)的,STORKE设置虚线 paint.setStyle(Paint.Style.STROKE);//设置虚线颜色 paint.setColor(Color.BLACK);Path path = new Path();//起点path.moveTo(0,200);//终点path.lineTo(1280,200);//那么虚线的一个单位就是由5像素实线,5像素空白,5像素实线,5像素空白组成的虚线段。PathEffect effects = new DashPathEffect(new float[]{5,5,5,5},1);//将样式放入直线中 paint.setPathEffect(effects);canvas.drawPath(path,paint);}
canvas.drawPath方法:传送门
Path类包含了由直线、二次曲线、三次曲线组成多种符合的集合路径图形,它可以用canvas.drawPath()来绘制,并且可以使填充的或者描边的(是基于paint的style的),并且它可以用于裁剪或者在一条path上面绘制文本。
Canvas只有drawLine
方法,没有drawDashLine
方法。但是你要知道,画什么虽然是Canvas决定的,但是怎么画却是由画笔Paint决定的
Paint有setPathEffect(PathEffect effect)
这么一个方法,PathEffect一共有六个子类:传送门 ComposePathEffect, CornerPathEffect, DashPathEffect, DiscretePathEffect, PathDashPathEffect, SumPathEffect, 其中的DashPathEffect就是我们需要的虚线效果
二、在activity_main文件中引入自定义控件DashedLine 添加引用该自定义空间所在位置的绝对路径 <com.example.asus.gary_042.DashedLine>
<com.example.asus.gary_042.DashedLineandroid:id="@+id/dashedLine"android:layout_width="match_parent"android:layout_height="match_parent" />