1. 程式人生 > >Android刮彩票效果

Android刮彩票效果

這裡寫圖片描述

實現分析:
1.底部一張圖片
2.圖片頭部是一個矩形遮擋圖片
3.通過滑動監聽,讓矩形缺失,露出底部圖片

這裡寫圖片描述
主要程式碼如下:


    private RectF rectf;
    private Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
            R.drawable.test);
    //頭部
    private Canvas headCanvas;
    private int width;
    private int height;
    // 開始繪製Path座標
private float startX; private float startY; // 用來繪製劃過的路徑 private Path path = new Path(); // 劃過多大距離開始繪製劃過的路徑 private static final int DIS = 20; // 畫筆 private Paint paint; // 畫筆size private int paintSize = 20; @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub
width = getWidth(); height = getHeight(); paintSize = height / 5; rectf = new RectF(0, 0, width, height); // 底部的文字 canvas.drawBitmap(bitmap, null, rectf, null); // 擋住底部文字 canvas.drawBitmap(drawHead(), null, rectf, null); } // 頭部的圖層 private
Bitmap drawHead() { Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); headCanvas = new Canvas(bitmap); RectF rectF = new RectF(0, 0, width, height); paint = new Paint(); paint.setColor(Color.BLACK); // 畫一個矩陣擋住底部 headCanvas.drawRect(rectF, paint); /* * 設定圖層混合模式 Mode.SRC_OUT:在不相交的地方繪製 源影象 */ paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT)); paint.setAlpha(0); paint.setAntiAlias(true); paint.setStrokeWidth(paintSize); /* * 設定畫筆的形狀 */ paint.setStyle(Paint.Style.STROKE); // 前圓角 paint.setStrokeJoin(Paint.Join.ROUND); // 後圓角 paint.setStrokeCap(Paint.Cap.ROUND); // 繪製滑動路徑 headCanvas.drawPath(path, paint); return bitmap; } // 重新整理 public void setRefresh() { // 清除路徑 path.rewind(); invalidate(); } // 切換圖片 public void setImage(Bitmap bitmap) { path.rewind(); this.bitmap = bitmap; invalidate(); } @Override public boolean dispatchTouchEvent(MotionEvent event) { // TODO Auto-generated method stub switch (event.getAction()) { case MotionEvent.ACTION_DOWN: startX = event.getX(); startY = event.getY(); // 移動起點 path.moveTo(startX, startY); invalidate(); break; case MotionEvent.ACTION_MOVE: float differenceX = Math.abs(event.getX() - startX); float differenceY = Math.abs(event.getY() - startY); if (differenceX >= DIS || differenceY >= DIS) { /* * 引數1,2:為控制點 引數3,4:為結束點 */ path.quadTo(startX, startY, event.getX(), event.getY()); startX = event.getX(); startY = event.getY(); } invalidate(); break; case MotionEvent.ACTION_UP: break; default: break; } return true; }

原始碼下載