在Android上使用虛線總會(huì)有各種麻煩事情。這里貼一個(gè)簡(jiǎn)單的自定義View實(shí)現(xiàn)虛線的代碼厅篓。
目前寫好的可自定義內(nèi)容:
- 線寬
- 線的顏色
- 每節(jié)虛線的寬度
- 每節(jié)虛線的間隔
- 方向
- 有其他需求的小伙伴自行添加吧,代碼挺簡(jiǎn)單的剧董。
java代碼:
/**
* Created by CZH on 2017/6/12.
* 虛線
*/
public class ImaginaryLine extends View {
private Paint linePaint;
private int orientation;
private Path path;
public ImaginaryLine(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public ImaginaryLine(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(AttributeSet attrs) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ImaginaryLine);
int lineColor = typedArray.getColor(R.styleable.ImaginaryLine_lineColor, Color.parseColor("#CACACA"));
float lineWidth = typedArray.getDimension(R.styleable.ImaginaryLine_lineWidth, 10);
float imaginaryWidth = typedArray.getDimension(R.styleable.ImaginaryLine_imaginary_width, 5);
float intervalWidth = typedArray.getDimension(R.styleable.ImaginaryLine_interval_width, 5);
orientation = typedArray.getInteger(R.styleable.ImaginaryLine_lineOrientation, 2);
typedArray.recycle();
linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
linePaint.setColor(lineColor);
linePaint.setStyle(Paint.Style.STROKE);
linePaint.setStrokeWidth(lineWidth);
PathEffect effects = new DashPathEffect(new float[]{imaginaryWidth, intervalWidth}, 0.0f);//設(shè)置虛線的間隔和點(diǎn)的長(zhǎng)度
linePaint.setPathEffect(effects);
}
@Override
public void layout(@Px int l, @Px int t, @Px int r, @Px int b) {
super.layout(l, t, r, b);
if (path != null)
path.reset();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
if (path == null) {
path = new Path();
}
if (path.isEmpty()) {
if (orientation == 1) {
path.moveTo(getMeasuredWidth() / 2, 0);
path.lineTo(getMeasuredWidth() / 2, getMeasuredHeight());
} else {
path.moveTo(0, getMeasuredHeight() / 2);
path.lineTo(getMeasuredWidth(), getMeasuredHeight() / 2);
}
}
canvas.drawPath(path, linePaint);
}
public void setLineColor(int color) {
linePaint.setColor(color);
invalidate();
}
}
attrs:
<!--虛線-->
<declare-styleable name="ImaginaryLine">
<!--方向-->
<attr name="lineOrientation">
<enum name="vertical" value="1" />
<enum name="horizontal" value="2" />
</attr>
<!--顏色-->
<attr name="lineColor" format="color" />
<!--線寬-->
<attr name="lineWidth" format="dimension" />
<!--每節(jié)虛線的寬-->
<attr name="imaginary_width" format="dimension"/>
<!--每節(jié)虛線的間隔-->
<attr name="interval_width" format="dimension"/>
</declare-styleable>
OK 到此結(jié)束赶熟。代碼很簡(jiǎn)單,就沒寫注釋~