Android自定义View之绘制虚线

现在实现一个效果,有个虚线分割和阴影效果。一个一个实现。

分为2中方式。

1.设计出图,我们SRC引入进来(最简单,但是需要其他资源支持)。

2.code实现,有些难度,需要查资料。

现在把第2种方式的实现给贴出来。

最简单的方法是利用ShapeDrawable,比如说你想用虚线要隔开两个控件,就可以在这两个控件中加个View,然后给它个虚线背景。嗯,理论上就是这样子的,实现上也很简单。

<!-- drawable 文件 -->
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line"> <stroke android:width="1dp" android:color="@color/dash_line" android:dashGap="2dp" android:dashWidth="3dp"/> </shape>
 
 


public class DashLineView extends View {


private Paint mPaint;


public DashLineView(Context context, AttributeSet attrs) {

super(context, attrs);


mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

mPaint.setColor(getResources().getColor(R.color.dash_line));

mPaint.setStrokeWidth(3);

mPaint.setPathEffect(new DashPathEffect(new float[] {5, 5}, 0));


}

@Override

protected void onDraw(Canvas canvas) {

int centerY = getHeight() / 2;

setLayerType(LAYER_TYPE_SOFTWARE, null);

canvas.drawLine(0, centerY, getWidth(), centerY, mPaint);

}
}

public class DashLineView extends View {

 

    private Paint mPaint;

    private Path mPath;

 

    public DashLineView(Context context, AttributeSet attrs) {

        super(context, attrs);

 

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        mPaint.setColor(getResources().getColor(R.color.dash_line));

        // 需要加上这句,否则画不出东西

        mPaint.setStyle(Paint.Style.STROKE);

        mPaint.setStrokeWidth(3);

        mPaint.setPathEffect(new DashPathEffect(new float[] {15, 5}, 0));

 

        mPath = new Path();

    }

 

    @Override

    protected void onDraw(Canvas canvas) {

        int centerY = getHeight() / 2;

        mPath.reset();

        mPath.moveTo(0, centerY);

        mPath.lineTo(getWidth(), centerY);

        canvas.drawPath(mPath, mPaint);

    }

}

至此,我们已经完美的实现了虚线的绘制,但本篇文章还没完呢!我们绘制出来的虚线是一个实心矩形,那如果我们要求这条是由实心圆形组成的呢?又或者是其它图形组成的呢?这时候我们就可以用PathDashPathEffect来实现了,看清楚点,是PathDashPathEffect而不是DashPathEffect!PathDashPathEffect允许我们添加一个路径来定义虚线的样式。我们把setPathEffect()改一下,看看效果。

Path path = new Path();
path.addCircle(0, 0, 3, Path.Direction.CW); mPaint.setPathEffect(new PathDashPathEffect(path, 15, 0, PathDashPathEffect.Style.ROTATE));


作者:Android杂货铺
链接:https://www.jianshu.com/p/75cc93195f7a
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

转载于:https://www.cnblogs.com/wcLT/p/8399655.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值