Android自定义布局实现优惠券效果

最近需要实现一个凹凸效果的拟物化优惠券效果,我一看,本来想用.9图片做背景实现的,虽说图片做背景实现省事儿方便,但是能用代码实现最好不过了,最终我还是选择了用代码来实现,于是有了下文。

最终效果图

demo下载地址

1.完整代码

先看完整的代码,后面我们再对代码逐一的解释

public class CouponDisplayView extends RelativeLayout {

    private Paint mPaint;
    private Paint mPaint2;
// 圆间距
    private float gap = 0;
// 半径
    private float radius = 20;
// 圆数量
    private int circleNum;
    private float remain;
    private int color;

    public CouponDisplayView(Context context) {
        super(context);
    }
    public CouponDisplayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setDither(true);
        mPaint.setColor(color);
        mPaint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (remain == 0) {
            remain = (int) (w - gap) % (2 * radius + gap);
        }
        circleNum = (int) ((w - gap) / (2 * radius + gap));

    }
    public CouponDisplayView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < circleNum; i++) {
            float x = gap + radius + remain / 2 + ((gap + radius * 2) * i);
            canvas.drawCircle(x, 0, radius, mPaint);
        }
        mPaint2 = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint2.setDither(true);
        mPaint2.setColor(getResources().getColor(R.color.divider_color_car));
        mPaint2.setStyle(Paint.Style.FILL);

        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.DKGRAY);
        Path path = new Path();
        path.moveTo(0, getHeight() / 2 + 60);
        path.lineTo(getWidth(), getHeight() / 2 + 60);
        PathEffect effects = new DashPathEffect(new float[]{15, 15, 15, 15}, 2);
        paint.setPathEffect(effects);
        canvas.drawPath(path, paint);
        canvas.drawCircle(0, getHeight() / 2 + 60, radius, mPaint2);
        canvas.drawCircle(getWidth(), getHeight() / 2 + 60, radius, mPaint2);
    }
    public void setColor(int color) {
        this.color = color;
    }
}

2.方法解释

1、CouponDisplayView继承自RelativeLayout,通过打印日志测试已知View的执行顺序如下:

CouponDisplayView(context,attrs,defStyleAttr)
CouponDisplayView(context,attrs)
onSizeChanged()
onDraw()

onSizeChanged(int w, int h, int oldw, int oldh)
当view的大小发生变化时触发
onDraw(Canvas canvas)
负责将View绘制在屏幕上
public CouponDisplayView(Context context)
Java代码直接new一个CouponDisplayView实例的时候,会调用这个只有一个参数的构造函数
public CouponDisplayView(Context context, AttributeSet attrs)
在默认的XML布局文件中创建的时候调用这个有两个参数的构造函数。AttributeSet类型的参数负责把XML布局文件中所自定义的属性通过AttributeSet带入到View内;
public CouponDisplayView(Context context,AttributeSet attrs, int defStyleAttr)
构造函数中第三个参数是默认的Style,这里的默认的Style是指它在当前Application或者Activity所用的Theme中的默认Style,且只有在明确调用的时候才会调用

3.代码实现思路

从上面的效果图来看,这个自定义View和普通的Linearlayout,RelativeLayout一样,只是上下两边多了类似于半圆锯齿的形状,我们需要在上下两条线上画一个个白色的小圆来实现这种效果。
假如我们上下线的半圆以及半圆与半圆之间的间距是固定的,那么不同尺寸的屏幕肯定会画出不同数量的半圆,那么我们只需要根据控件的宽度来获取能画的半圆数。
我们观察效果图会发现,圆的数量总是圆间距数量-1,

也就是说,假设圆的数量是circleNum,那么圆间距就是circleNum+1,所以我们可以根据这个计算出circleNum: 这里gap就是圆间距,radius是圆半径,w是view的宽

circleNum = (int) ((w-gap)/(2*radius+gap));

1 、重写onSizeChanged()方法,根据上面的圆的半径和圆间距来计算需要画的圆数量circleNum

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (remain == 0) {
            remain = (int) (w - gap) % (2 * radius + gap);
        }
        circleNum = (int) ((w - gap) / (2 * radius + gap));
    }

2.接下来只需要重写onDraw()方法,简单的根据circleNum的数量将一个一个的圆绘制在屏幕上

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
       for (int i = 0; i < circleNum; i++) {
            float x = gap + radius + remain / 2 + ((gap + radius * 2) * i);
            canvas.drawCircle(x, 0, radius, mPaint);
        }
}

3.画中间的黑色虚线

  Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.DKGRAY);
        Path path = new Path();
        path.moveTo(0, getHeight() / 2 + 60);
        path.lineTo(getWidth(), getHeight() / 2 + 60);
        PathEffect effects = new DashPathEffect(new float[]{15, 15, 15, 15}, 2);
        paint.setPathEffect(effects);
        canvas.drawPath(path, paint);

4.画两边居中的半圆

    mPaint2 = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint2.setDither(true);
        mPaint2.setColor(getResources().getColor(R.color.divider_color_car));
        mPaint2.setStyle(Paint.Style.FILL);
      canvas.drawCircle(0, getHeight() / 2 + 60, radius, mPaint2);
        canvas.drawCircle(getWidth(), getHeight() / 2 + 60, radius, mPaint2);

代码分析完毕

3.设置自定义样式属性

考虑到复用地方不是很多,所以上面的代码没有写自定义样式属性,而是用了public void setColor(int color) {this.color = color;}有需要设置自定义属性的我在这里写一下哈,嘻嘻

1、在res/values/ 下建立一个attr.xml , 在里面定义我们的需要用到的属性以及声明相对应属性的取值类型

<?xml version="1.0" encoding="utf-8"?>
<resources>
    //半圆颜色
    <attr name="radiusColor" format="color" />
    <declare-styleable name="CouponDisplayView">
        <attr name="radiusColor" />
    </declare-styleable>

</resources>

上面定义的半圆颜色的属性,format属性的取值类型总共有10种,包括:stringcolordemensionintegerenumreferencefloatbooleanfractionflag

2、然后在XML布局中声明我们的自定义View

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<--注意:一定要引入xmlns:custom="http://schemas.android.com/apk/res-auto"
custom名字可以自定义-->
    <com.xxx.xxx.CouponDisplayView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FBB039"
        android:orientation="horizontal"
        android:padding="16dp"
        custom:radiusColor="@Color/red">
............
    </com.xxx.xxx.CouponDisplayView>
</LinearLayout>

3、在View的构造方法中,获得我们的xml布局文件中定义的颜色

public CouponDisplayView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        Log.d("mDebug", "CouponDisplayView context,attrs,defStyleAttr");
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CouponDisplayView, defStyleAttr, 0);
        for (int i = 0; i < a.getIndexCount(); i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.CouponDisplayView_radiusColor:
                    radius = a.getDimensionPixelSize(R.styleable.CouponDisplayView_radiusColor, 10);
                    break;
            }
        }
        a.recycle();
}

OK,设置自定义样式属性到此就写完了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,122评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,070评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,491评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,636评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,676评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,541评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,292评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,211评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,655评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,846评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,965评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,684评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,295评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,894评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,012评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,126评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,914评论 2 355

推荐阅读更多精彩内容