自定义视图-马赛克视图

这里我是直接继承的ImageView,主要是为了能兼容之前的项目,因为之前是直接用的ImageView。

思路

  1. 根据原图片生成一个全马赛克的图片
  2. 监听手势,得到应该显示的马赛克方块的集合
  3. 根据方块的集合,刷新视图,这里用到了Paint的Xfermode(图片混合模式)
    1. 手势图和全马赛克图混合,在相交处绘制马赛克图
    2. 将上一步的图和原图混合,在相交处绘制上一步的图,在不相交处绘制原图,搞定收工!

效果图

源码

package com.che.carcheck.support.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

/** * 马赛克视图 * <p/> * 作者:余天然 on 16/5/30 下午6:04 */
public class MosaicView extends ImageView {

    private Bitmap bitmap;//原图
    private Bitmap mosaicBitmap;//全马赛克图
    private Bitmap mergeBitmap;//合成图
    private int strokeWidth;// 画笔宽度px
    private List<Rect> mosaicRects;//马赛克集合
    public static final int min_mosaic_block_size = 4;//马赛克的最小粒度
    private Paint paint;

    public MosaicView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mosaicRects = new ArrayList<>();
        strokeWidth = 20;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                int x = (int) event.getX();
                int y = (int) event.getY();
                //记录应该显示马赛克的矩形集合
                int radius = strokeWidth / 2;
                int left = Math.max(x - radius, 0);
                int right = Math.min(x + radius, bitmap.getWidth());
                int top = Math.max(y - radius, 0);
                int bottom = Math.min(y + radius, bitmap.getHeight());
                Rect rect = new Rect(left, top, right, bottom);
                mosaicRects.add(rect);
                // FIXME: 16/5/30 这里本来打算调用onDraw的,不知道setImageBitmap那里怎么出了问题
// invalidate();
                updateMosaicList();
                break;
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
// doDraw(canvas);
    }

    private void updateMosaicList() {
        Canvas canvas = new Canvas();
        doDraw(canvas);
        setImageBitmap(mergeBitmap);
    }

    private void doDraw(Canvas canvas) {
        //手势图
        Bitmap touchBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
        canvas.setBitmap(touchBitmap);
        for (Rect rect : mosaicRects) {
            canvas.drawRect(rect, paint);
        }

        //合成图
        mergeBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
        canvas.setBitmap(mergeBitmap);
        canvas.drawBitmap(mosaicBitmap, 0, 0, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        canvas.drawBitmap(touchBitmap, 0, 0, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));
        canvas.drawBitmap(bitmap, 0, 0, paint);
    }

    //生成全马赛克的图片
    private Bitmap makeMosaic(Bitmap bitmap, Rect targetRect,
                              int blockSize) throws OutOfMemoryError {
        if (bitmap == null || bitmap.getWidth() == 0 || bitmap.getHeight() == 0
                || bitmap.isRecycled()) {
            throw new RuntimeException("bad bitmap to add mosaic");
        }
        if (blockSize < min_mosaic_block_size) {
            blockSize = min_mosaic_block_size;
        }
        if (targetRect == null) {
            targetRect = new Rect();
        }
        int bw = bitmap.getWidth();
        int bh = bitmap.getHeight();
        if (targetRect.isEmpty()) {
            targetRect.set(0, 0, bw, bh);
        }
        //
        int rectW = targetRect.width();
        int rectH = targetRect.height();
        int[] bitmapPxs = new int[bw * bh];
        // fetch bitmap pxs
        bitmap.getPixels(bitmapPxs, 0, bw, 0, 0, bw, bh);
        //
        int rowCount = (int) Math.ceil((float) rectH / blockSize);
        int columnCount = (int) Math.ceil((float) rectW / blockSize);
        int maxX = bw;
        int maxY = bh;
        for (int r = 0; r < rowCount; r++) { // row loop
            for (int c = 0; c < columnCount; c++) {// column loop
                int startX = targetRect.left + c * blockSize + 1;
                int startY = targetRect.top + r * blockSize + 1;
                dimBlock(bitmapPxs, startX, startY, blockSize, maxX, maxY);
            }
        }
        return Bitmap.createBitmap(bitmapPxs, bw, bh, Bitmap.Config.ARGB_8888);
    }

    //从块内取样,并放大,从而达到马赛克的模糊效果
    private static void dimBlock(int[] pxs, int startX, int startY,
                                 int blockSize, int maxX, int maxY) {
        int stopX = startX + blockSize - 1;
        int stopY = startY + blockSize - 1;
        if (stopX > maxX) {
            stopX = maxX;
        }
        if (stopY > maxY) {
            stopY = maxY;
        }
        //
        int sampleColorX = startX + blockSize / 2;
        int sampleColorY = startY + blockSize / 2;
        //
        if (sampleColorX > maxX) {
            sampleColorX = maxX;
        }
        if (sampleColorY > maxY) {
            sampleColorY = maxY;
        }
        int colorLinePosition = (sampleColorY - 1) * maxX;
        int sampleColor = pxs[colorLinePosition + sampleColorX - 1];// 像素从1开始,但是数组层0开始
        for (int y = startY; y <= stopY; y++) {
            int p = (y - 1) * maxX;
            for (int x = startX; x <= stopX; x++) {
                // 像素从1开始,但是数组层0开始
                pxs[p + x - 1] = sampleColor;
            }
        }
    }

    /*设置原图*/
    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
        this.mosaicBitmap = makeMosaic(bitmap, null, strokeWidth);
        updateMosaicList();
    }

    /*获取合成图*/
    public Bitmap getMergeBitmap() {
        return mergeBitmap;
    }

    /*恢复初始的原图*/
    public void reset() {
        this.mosaicRects.clear();
        updateMosaicList();
    }

    /*设置画笔宽度*/
    public void setStrokeWidth(int strokeWidth) {
        this.strokeWidth = strokeWidth;
        this.mosaicBitmap = makeMosaic(bitmap, null, strokeWidth);
        updateMosaicList();
    }


}

你可能感兴趣的:(自定义视图-马赛克视图)