zoukankan      html  css  js  c++  java
  • 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
    來源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    iOS 内购讲解
    实现抓图的工具2
    实现抓图的工具
    关于胖客户端
    实时进销存
    DataGridView隔行显示不同的颜色
    C#数据库绑定
    VS2012中数据库架构的比较
    delphi使用outputdebugstring调试程序和写系统日志
    drupal7安装中文错误
  • 原文地址:https://www.cnblogs.com/wcLT/p/8399655.html
Copyright © 2011-2022 走看看