试了很多网上的代码总是不行,最好的情况是在自己的布局文件里预览是正确的,运行到真机却显示一条直线
后来搞了很久终于搞定:
package com.fhc.view;
import com.fhc.android.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
/**
* 点划线
* @author fanhoucheng
* @Email fanhoucheng@sina.com
* @版权所有 Copyright © 2014 fanhoucheng, All Rights Reserved.
* @使用说明 可在xml中设置horizontal属性,以描绘横线还是纵线
* 需要修改点划线样式请修改DashPathEffect(new float[] {3, 3}, 0)中的数值
* xmlns:fhc="http://schemas.android.com/apk/res/com.fhc.android
* <com.fhc.view.DashDotLineView
* fhc:horizontal="true" />
*/
public class DashDotLineView extends View{
Context context;
boolean horizontal = false;
public DashDotLineView(Context context) {
super(context);
this.context = context;
}
public DashDotLineView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
this.context = context;
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
private void init(Context context, AttributeSet attrs) {
if (attrs != null) {
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.DashDotLineView, 0, 0);
horizontal = a
.getBoolean(R.styleable.DashDotLineView_horizontal, false);
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
Paint mLinePaint = new Paint();
Bitmap background = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_4444);
canvas.drawBitmap(background, 0, 0, null);
// 画虚线
mLinePaint.setColor(this.context.getResources().getColor(R.color.black) );
DashPathEffect effect = new DashPathEffect(new float[] {3, 3}, 0);
mLinePaint.setAntiAlias(true);
mLinePaint.setPathEffect(effect);
mLinePaint.setStyle(Paint.Style.STROKE);
mLinePaint.setStrokeWidth(2);
mLinePaint.setSubpixelText(true);
if(horizontal){
canvas.drawLine(0, 0, getWidth(), 0, mLinePaint);
}else{
canvas.drawLine(0, 0, 0, getHeight(), mLinePaint);
}
}
}