標籤:集合 utf-8 href int() com bsp 使用 play 就是
在Abdroid螢幕中繪製虛線,最通用的是自訂控制項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 2018/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="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.asus.gary_042.MainActivity"> <com.example.asus.gary_042.DashedLine android: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.DashedLine android:id="@+id/dashedLine" android:layout_width="match_parent" android:layout_height="match_parent" />
Android_(控制項)使用自訂控制項在螢幕中繪製一條虛線