学习篇---刮刮卡

来源:互联网 发布:我的世界起床战争端口 编辑:程序博客网 时间:2024/05/16 09:09

效果图:


GuaGuaKa.java

import android.content.Context;import android.content.res.TypedArray;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Path;import android.graphics.PorterDuff;import android.graphics.PorterDuffXfermode;import android.graphics.Rect;import android.graphics.RectF;import android.util.AttributeSet;import android.util.TypedValue;import android.view.MotionEvent;import android.view.View;/** * Created by Administrator on 2016/5/24. */public class GuaGuaKa extends View {    private Paint sweepPaint;//擦除的画笔    private Canvas mCanvas;//起缓存作用的画布    private Path sweepPath;//擦除的路径    private Bitmap mBitmap;//与刮刮卡大小相同的图片    private Bitmap bgBitmap;//刮刮卡的表面图片    private Paint textPaint;//文本画笔    private Paint bgPanit;//表面图片画笔    private Rect textBound;//用于储存文字的长和宽    private int textSize;//文本的大小    private int textColor;//文本颜色    private String text;//文本内容    private volatile boolean isComplete;//是否擦除完毕    private OnCompleteListener  onCompleteListener;//擦除完毕调用的回调接口    public GuaGuaKa(Context context) {        this(context, null);    }    public GuaGuaKa(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    public GuaGuaKa(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        bgBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.fg_guaguaka);        //获取自定义属性        TypedArray typedArray=context.getTheme().obtainStyledAttributes(attrs,R.styleable.GuaGuaKa,defStyleAttr,0);        textColor=typedArray.getColor(R.styleable.GuaGuaKa_textColor,Color.RED);        textSize= (int) typedArray.getDimension(R.styleable.GuaGuaKa_textSize, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,25,getResources().getDisplayMetrics()));//默认的字体大小是25sp,转化为px        text=typedArray.getString(R.styleable.GuaGuaKa_text);        typedArray.recycle();        if(text==null){            text="谢谢惠顾";        }        init();    }//初始化画笔    private void init() {        bgPanit=new Paint();        bgPanit.setAntiAlias(true);        bgPanit.setColor(Color.parseColor("#c0c0c0"));        bgPanit.setStyle(Paint.Style.FILL);        sweepPath = new Path();        sweepPaint = new Paint();        sweepPaint.setAntiAlias(true);        sweepPaint.setDither(true);        sweepPaint.setStrokeCap(Paint.Cap.ROUND);        sweepPaint.setStrokeJoin(Paint.Join.ROUND);        sweepPaint.setStrokeWidth(20);        sweepPaint.setStyle(Paint.Style.STROKE);        textPaint=new Paint();        textPaint.setTextSize(textSize);        textPaint.setColor(textColor);        textPaint.setStyle(Paint.Style.STROKE);        textBound=new Rect();        textPaint.getTextBounds(text,0, text.length(),textBound);//获取文本的长宽    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        int width = getMeasuredWidth();        int height = getMeasuredHeight();        mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);        mCanvas = new Canvas(mBitmap);//创建画布        mCanvas.drawRoundRect(new RectF(0,0,getMeasuredWidth(),getMeasuredHeight()),30,30,bgPanit);//画圆角矩形        mCanvas.drawBitmap(bgBitmap,null,new RectF(0,0,getMeasuredWidth(),getMeasuredHeight()),bgPanit);//画刮刮卡表面图片    }    @Override    public boolean onTouchEvent(MotionEvent event) {        int action = event.getAction();        float x = event.getX();        float y = event.getY();        switch (action) {            case MotionEvent.ACTION_DOWN:                sweepPath.moveTo(x, y);                break;            case MotionEvent.ACTION_MOVE:                sweepPath.lineTo(x, y);                break;            case MotionEvent.ACTION_UP:                runnable.run();                break;        }        invalidate();        return true;    }    //线程用于计算已经被擦除的像素量    private Runnable runnable=new Runnable() {        @Override        public void run() {            int widthPx=getWidth();            int heightPx=getHeight();            int sweepArea=0;            int totalArea=widthPx*heightPx;            int totalPx[]=new int[totalArea];            int percentPx;            mBitmap.getPixels(totalPx,0,mBitmap.getWidth(),0,0,mBitmap.getWidth(),mBitmap.getHeight());            for(int i=0;i<widthPx;i++){                for(int j=0;j<heightPx;j++){                   int dex=i+j*widthPx;                    if(totalPx[dex]==0){                        sweepArea++;                    }                }            }            percentPx=sweepArea*100/totalArea;//            Log.e("percentPx",percentPx+"" );            if(percentPx>50){                isComplete=true;                postInvalidate();            }        }    };    public interface OnCompleteListener{        public void onComlete();    }    public void setOnCompleteListener(OnCompleteListener onCompleteListener) {        this.onCompleteListener = onCompleteListener;    }    @Override    protected void onDraw(Canvas canvas) {        //画文本        canvas.drawText(text,getWidth()/2-textBound.width()/2,getHeight()/2+textBound.height()/2,textPaint);        if(!isComplete) {            sweepPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));//设置画笔xformode            mCanvas.drawPath(sweepPath, sweepPaint);            canvas.drawBitmap(mBitmap, 0, 0, null);        }        if(isComplete){            if (onCompleteListener!=null){                onCompleteListener.onComlete();                onCompleteListener=null;//防止再次被调用            }        }    }    //设置文本内容    public void setText(String text){        textPaint.getTextBounds(text,0, text.length(),textBound);        this.text=text;        invalidate();    }    public String getText(){        return text;    }}
attrs.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="GuaGuaKa">        <attr name="text" format="string"/>        <attr name="textSize" format="dimension"/>        <attr name="textColor" format="color"/>    </declare-styleable></resources>
MainActivity.java

import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.Toast;public class MainActivity extends AppCompatActivity {private GuaGuaKa guaGuaKa;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        guaGuaKa= (GuaGuaKa) findViewById(R.id.guaguaKa);        guaGuaKa.setText("妹纸一位");        guaGuaKa.setOnCompleteListener(new GuaGuaKa.OnCompleteListener() {            @Override            public void onComlete() {                Toast.makeText(MainActivity.this,"恭喜你获得了:"+guaGuaKa.getText(),Toast.LENGTH_SHORT).show();            }        });    }}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:songdongwan="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.songdongwan.guguka.MainActivity"><com.songdongwan.guguka.GuaGuaKa    android:id="@+id/guaguaKa"    songdongwan:textSize="35sp"    songdongwan:textColor="#f00"    android:layout_centerInParent="true"    android:layout_width="300dp"    android:layout_height="100dp" /></RelativeLayout>

参考博客地址:文章地址

0 0
原创粉丝点击