自定义 view 实现兑奖券背景[初级]

自定义 view 实现兑奖券背景[初级]_第1张图片

[核心思路]

  • 继承LinearLayout,重写三个构造函数(串联构造函数)
  • 固定模式,重写自定义view要实现的三个方法
    ###[核心代码如下]
public class LotteryView extends LinearLayout{
    private Paint mPaint;
    private float mRadious =6;  //半径
    private float mGap =5;  //边缘锯齿的间隙
    private int mCircleNumX; //横向 边缘锯齿圆的数量
    private int mCircleNumY; //纵向 边缘锯齿圆的数量

    public LotteryView(Context context) {
        super(context);
    }

    public LotteryView(Context context,  AttributeSet attrs) {
        super(context, attrs);
        //1.画笔初始化
        mPaint = new Paint();
        mPaint.setDither(true);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(Color.WHITE);

    }

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

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //2.指定边缘锯齿绘制的数量
        mCircleNumX=(int)((w-mGap)/(mRadious*2+mGap));
        mCircleNumY=(int)((h-mGap)/(mRadious*2+mGap));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //3.指定每一个圆心的位置并画圆和填充中间矩形
        for (int i = 0; i <mCircleNumX ; i++) {
        float radiousX=mGap+mRadious+((mRadious*2+mGap)*i);
        float radiousY=mGap+mRadious+((mRadious*2+mGap)*i);
            //绘制上面
            canvas.drawCircle(radiousX,0,mRadious,mPaint);
            //绘制左面
            canvas.drawCircle(0,radiousY,mRadious,mPaint);
            //绘制右面
            canvas.drawCircle(getWidth(),radiousY,mRadious,mPaint);
            //绘制下面
            canvas.drawCircle(radiousX,getHeight(),mRadious,mPaint);

        }
    }
}

###[直接在布局中引用]


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="50dp"
    android:orientation="vertical"
    tools:context="com.jing.www.lotterydemo.MainActivity">
    <com.jing.www.lotterydemo.LotteryView
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:background="#7E30B8DA"
        tools:ignore="MissingConstraints">
    com.jing.www.lotterydemo.LotteryView>
    <com.jing.www.lotterydemo.LotteryView
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:background="#8A3CAC"
        tools:ignore="MissingConstraints">
    com.jing.www.lotterydemo.LotteryView>
    <com.jing.www.lotterydemo.LotteryView
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:background="#59DB22"
        tools:ignore="MissingConstraints">
    com.jing.www.lotterydemo.LotteryView>
LinearLayout>

###[Demo地址]
https://github.com/EugeniaGao/LotteryDemo

温柔的小哥哥和漂亮小姐姐,喜欢要点点赞哦~

你可能感兴趣的:(Android,开发日常)