android 自定义划线,Android点划线自定义View

试了很多网上的代码总是不行,最好的情况是在自己的布局文件里预览是正确的,运行到真机却显示一条直线

后来搞了很久终于搞定:

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);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值