android 手寫簽名、畫板(自定義視圖)的使用

一、自定義一個視圖(代碼貼在後面),重寫裏面的觸摸監聽、畫面渲染的方法(onTouchEvent、onDraw);每一個方法都有解釋,很容易理解,直接嵌入項目使用
二、在項目中的使用:首先添加布局文件(代碼貼在後面),然後可以保持,也可以添加水印後再保存

String title = e_address+ “\n” + DateUtils.getFormatDate(new Date());//水印信息
Bitmap bitmapAddWater = ImageFactory.watermarkBitmap(linePathView.getBitMap(),null, title);//添加水印
ImageFactory.storeImage(bitmapAddWater,signatureFile);//保持該畫板的簽名信息(參數:圖片bitmap,存儲的文件路徑)
三、總的來說比較簡單,大家有疑問的可以和我留言,共同進步

佈局文件
<com.dfwy.cxy.xiahubao.customView.LinePathView
            android:id="@+id/linePathView"
            android:layout_width="match_parent"
            android:layout_height="160dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="10dp"
            android:background="@color/colorWhite"
            android:focusable="true"
            android:focusableInTouchMode="true" />
1、下面是自定義的一個畫板

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.support.annotation.ColorInt;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by leven on 2016/10/25.
 */

public class LinePathView extends View {

    private Context mContext;

    /**
     * 筆畫X座標起點
     */
    private float mX;
    /**
     * 筆畫Y座標起點
     */
    private float mY;
    /**
     * 手寫畫筆
     */
    private final Paint mGesturePaint = new Paint();
    /**
     * 路徑
     */
    private final Path mPath = new Path();
    /**
     * 簽名畫筆
     */
    private Canvas cacheCanvas;
    /**
     * 簽名畫布
     */
    private Bitmap cachebBitmap;
    /**
     * 是否已經簽名
     */
    private boolean isTouched = false;
    /**
     * 畫筆寬度 px;
     */
    private int mPaintWidth = 10;
    /**
     * 前景色
     */
    private int mPenColor = Color.BLACK;
    /**
     * 背景色(指最終簽名結果文件的背景顏色,默認爲透明色)
     */
    private int mBackColor=Color.TRANSPARENT;
    public LinePathView(Context context) {
        super(context);
        init(context);
    }

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

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

    public void init(Context context) {
        this.mContext = context;
        //設置抗鋸齒
        mGesturePaint.setAntiAlias(true);
        //設置簽名筆畫樣式
        mGesturePaint.setStyle(Paint.Style.STROKE);
        //設置筆畫寬度
        mGesturePaint.setStrokeWidth(mPaintWidth);
        //設置簽名顏色
        mGesturePaint.setColor(mPenColor);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //創建跟view一樣大的bitmap,用來保存簽名
        cachebBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        cacheCanvas = new Canvas(cachebBitmap);
        cacheCanvas.drawColor(mBackColor);
        isTouched=false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                this.setFocusable(true);
                this.setFocusableInTouchMode(true);
                this.requestFocus();
                this.requestFocusFromTouch();
                touchDown(event);
                break;
            case MotionEvent.ACTION_MOVE:
                this.setFocusable(true);
                this.setFocusableInTouchMode(true);
                this.requestFocus();
                this.requestFocusFromTouch();
                isTouched = true;
                touchMove(event);
                break;
            case MotionEvent.ACTION_UP:
                this.setFocusable(true);
                this.setFocusableInTouchMode(true);
                this.requestFocus();
                this.requestFocusFromTouch();
                //將路徑畫到bitmap中,即一次筆畫完成纔去更新bitmap,而手勢軌跡是實時顯示在畫板上的。
                cacheCanvas.drawPath(mPath, mGesturePaint);
                mPath.reset();
                break;
        }
        // 更新繪製
        invalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //畫此次筆畫之前的簽名
        canvas.drawBitmap(cachebBitmap, 0, 0, mGesturePaint);
        // 通過畫布繪製多點形成的圖形
        canvas.drawPath(mPath, mGesturePaint);
    }

    // 手指點下屏幕時調用
    private void touchDown(MotionEvent event) {
        // 重置繪製路線
        mPath.reset();
        float x = event.getX();
        float y = event.getY();
        mX = x;
        mY = y;
        // mPath繪製的繪製起點
        mPath.moveTo(x, y);
    }

    // 手指在屏幕上滑動時調用
    private void touchMove(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final float previousX = mX;
        final float previousY = mY;
        final float dx = Math.abs(x - previousX);
        final float dy = Math.abs(y - previousY);
        // 兩點之間的距離大於等於3時,生成貝塞爾繪製曲線
        if (dx >= 3 || dy >= 3) {
            // 設置貝塞爾曲線的操作點爲起點和終點的一半
            float cX = (x + previousX) / 2;
            float cY = (y + previousY) / 2;
            // 二次貝塞爾,實現平滑曲線;previousX, previousY爲操作點,cX, cY爲終點
            mPath.quadTo(previousX, previousY, cX, cY);
            // 第二次執行時,第一次結束調用的座標值將作爲第二次調用的初始座標值
            mX = x;
            mY = y;
        }
    }
    /**
     * 清除畫板
     */
    public void clear() {
        if (cacheCanvas != null) {
            isTouched = false;
            //更新畫板信息
//            mGesturePaint.setColor(mPenColor);
//            cacheCanvas.drawColor(mBackColor);
//            mGesturePaint.setColor(mPenColor);
//            invalidate();

            mPath.reset();
            cacheCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
            invalidate();
        }
    }


    /**
     * 保存畫板
     * @param path 保存到路徑
     */
    public void save(String path)  throws IOException {
        save(path, false, 0);
    }

    /**
     * 保存畫板
     * @param path       保存到路徑
     * @param clearBlank 是否清除邊緣空白區域
     * @param blank  要保留的邊緣空白距離
     */
    public void save(String path, boolean clearBlank, int blank) throws IOException {

        Bitmap bitmap=cachebBitmap;
        //BitmapUtil.createScaledBitmapByHeight(srcBitmap, 300);//  壓縮圖片
        if (clearBlank) {
            bitmap = clearBlank(bitmap, blank);
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);

        byte[] buffer = bos.toByteArray();
        if (buffer != null) {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
            OutputStream outputStream = new FileOutputStream(file);
            outputStream.write(buffer);
            outputStream.close();
        }
    }

    /**
     * 獲取畫板的bitmap
     * @return
     */
    public Bitmap getBitMap()
    {
        setDrawingCacheEnabled(true);
        buildDrawingCache();
        Bitmap bitmap=getDrawingCache();
//        setDrawingCacheEnabled(false);
        return bitmap;
    }
    /**
     * 逐行掃描 清楚邊界空白。
     *
     * @param bp
     * @param blank 邊距留多少個像素
     * @return
     */
    private Bitmap clearBlank(Bitmap bp, int blank) {
        int HEIGHT = bp.getHeight();
        int WIDTH = bp.getWidth();
        int top = 0, left = 0, right = 0, bottom = 0;
        int[] pixs = new int[WIDTH];
        boolean isStop;
        //掃描上邊距不等於背景顏色的第一個點
        for (int y = 0; y < HEIGHT; y++) {
            bp.getPixels(pixs, 0, WIDTH, 0, y, WIDTH, 1);
            isStop = false;
            for (int pix : pixs) {
                if (pix != mBackColor) {
                    top = y;
                    isStop = true;
                    break;
                }
            }
            if (isStop) {
                break;
            }
        }
        //掃描下邊距不等於背景顏色的第一個點
        for (int y = HEIGHT - 1; y >= 0; y--) {
            bp.getPixels(pixs, 0, WIDTH, 0, y, WIDTH, 1);
            isStop = false;
            for (int pix : pixs) {
                if (pix != mBackColor) {
                    bottom = y;
                    isStop = true;
                    break;
                }
            }
            if (isStop) {
                break;
            }
        }
        pixs = new int[HEIGHT];
        //掃描左邊距不等於背景顏色的第一個點
        for (int x = 0; x < WIDTH; x++) {
            bp.getPixels(pixs, 0, 1, x, 0, 1, HEIGHT);
            isStop = false;
            for (int pix : pixs) {
                if (pix != mBackColor) {
                    left = x;
                    isStop = true;
                    break;
                }
            }
            if (isStop) {
                break;
            }
        }
        //掃描右邊距不等於背景顏色的第一個點
        for (int x = WIDTH - 1; x > 0; x--) {
            bp.getPixels(pixs, 0, 1, x, 0, 1, HEIGHT);
            isStop = false;
            for (int pix : pixs) {
                if (pix != mBackColor) {
                    right = x;
                    isStop = true;
                    break;
                }
            }
            if (isStop) {
                break;
            }
        }
        if (blank < 0) {
            blank = 0;
        }
        //計算加上保留空白距離之後的圖像大小
        left = left - blank > 0 ? left - blank : 0;
        top = top - blank > 0 ? top - blank : 0;
        right = right + blank > WIDTH - 1 ? WIDTH - 1 : right + blank;
        bottom = bottom + blank > HEIGHT - 1 ? HEIGHT - 1 : bottom + blank;
        return Bitmap.createBitmap(bp, left, top, right - left, bottom - top);
    }

    /**
     * 設置畫筆寬度 默認寬度爲10px
     *
     * @param mPaintWidth
     */
    public void setPaintWidth(int mPaintWidth) {
        mPaintWidth = mPaintWidth > 0 ? mPaintWidth : 10;
        this.mPaintWidth = mPaintWidth;
        mGesturePaint.setStrokeWidth(mPaintWidth);

    }


    public void setBackColor(@ColorInt int backColor)
    {
        mBackColor=backColor;
    }


    /**
     * 設置畫筆顏色
     *
     * @param mPenColor
     */
    public void setPenColor(int mPenColor) {
        this.mPenColor = mPenColor;
        mGesturePaint.setColor(mPenColor);
    }

    /**
     * 是否有簽名
     *
     * @return
     */
    public boolean getTouched() {
        return isTouched;
    }
}
2、下面是一個圖片處理的工具類,對於圖片的操作(保存、複製、獲取bitmap、壓縮、添加水印等)可以直接使用
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;

/**
 * 圖片壓縮的工具類
 * Created by leven on 2016/10/9.
 */
public class ImageFactory {

    /**
     * Get bitmap from specified image path
     *
     * @param imgPath
     * @return
     */
    public Bitmap getBitmap(String imgPath) {
        // Get bitmap through image path
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = false;
        newOpts.inPurgeable = true;
        newOpts.inInputShareable = true;
        // Do not compress
        newOpts.inSampleSize = 1;
        newOpts.inPreferredConfig = Config.RGB_565;
        return BitmapFactory.decodeFile(imgPath, newOpts);
    }

    /**
     * Store bitmap into specified image path
     *
     * @param bitmap
     * @param outPath
     * @throws FileNotFoundException
     */
    public static void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException {
        FileOutputStream os = new FileOutputStream(outPath);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);

        //BitmapUtil.createScaledBitmapByHeight(srcBitmap, 300);//  壓縮圖片

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);

        byte[] buffer = bos.toByteArray();
        if (buffer != null) {
            File file = new File(outPath);
            if (file.exists()) {
                file.delete();
            }
            OutputStream outputStream = new FileOutputStream(file);
            try {
                outputStream.write(buffer);
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Compress image by pixel, this will modify image width/height.
     * Used to get thumbnail
     *
     * @param imgPath image path
     * @param pixelW  target pixel of width
     * @param pixelH  target pixel of height
     * @return
     */
    public Bitmap ratio(String imgPath, float pixelW, float pixelH) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 開始讀入圖片,此時把options.inJustDecodeBounds 設回true,即只讀邊不讀內容
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Config.RGB_565;
        // Get bitmap info, but notice that bitmap is null now
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath, newOpts);

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 想要縮放的目標尺寸
        float hh = pixelH;// 設置高度爲240f時,可以明顯看到圖片縮小了
        float ww = pixelW;// 設置寬度爲120f,可以明顯看到圖片縮小了
        // 縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可
        int be = 1;//be=1表示不縮放
        if (w > h && w > ww) {//如果寬度大的話根據寬度固定大小縮放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的話根據寬度固定大小縮放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0) be = 1;
        newOpts.inSampleSize = be;//設置縮放比例
        // 開始壓縮圖片,注意此時已經把options.inJustDecodeBounds 設回false了
        bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
        // 壓縮好比例大小後再進行質量壓縮
        //        return compress(bitmap, maxSize); // 這裏再進行質量壓縮的意義不大,反而耗資源,刪除
        return bitmap;
    }

    /**
     * Compress image by size, this will modify image width/height.
     * Used to get thumbnail
     *
     * @param image
     * @param pixelW target pixel of width
     * @param pixelH target pixel of height
     * @return
     */
    public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, os);
        if (os.toByteArray().length / 1024 > 1024) {//判斷如果圖片大於1M,進行壓縮避免在生成圖片(BitmapFactory.decodeStream)時溢出
            os.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, os);//這裏壓縮50%,把壓縮後的數據存放到baos中
        }
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //開始讀入圖片,此時把options.inJustDecodeBounds 設回true了
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = pixelH;// 設置高度爲240f時,可以明顯看到圖片縮小了
        float ww = pixelW;// 設置寬度爲120f,可以明顯看到圖片縮小了
        //縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可
        int be = 1;//be=1表示不縮放
        if (w > h && w > ww) {//如果寬度大的話根據寬度固定大小縮放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的話根據寬度固定大小縮放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0) be = 1;
        newOpts.inSampleSize = be;//設置縮放比例
        //重新讀入圖片,注意此時已經把options.inJustDecodeBounds 設回false了
        is = new ByteArrayInputStream(os.toByteArray());
        bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        //壓縮好比例大小後再進行質量壓縮
        //      return compress(bitmap, maxSize); // 這裏再進行質量壓縮的意義不大,反而耗資源,刪除
        return bitmap;
    }

    /**
     * Compress by quality,  and generate image to the path specified
     *
     * @param image
     * @param outPath
     * @param maxSize target will be compressed to be smaller than this size.(kb)
     * @throws IOException
     */
    public static void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // scale
        int options = 100;
        // Store the bitmap into output stream(no compress)
        image.compress(Bitmap.CompressFormat.JPEG, options, os);
        // Compress by loop
        while (os.toByteArray().length / 1024 > maxSize) {
            // Clean up os
            os.reset();
            // interval 10
            options -= 10;
            image.compress(Bitmap.CompressFormat.JPEG, options, os);
        }

        // Generate compressed image file
        FileOutputStream fos = new FileOutputStream(outPath);
        fos.write(os.toByteArray());
        fos.flush();
        fos.close();
    }

    /**
     * Compress by quality,  and generate image to the path specified
     *
     * @param imgPath
     * @param outPath
     * @param maxSize     target will be compressed to be smaller than this size.(kb)
     * @param needsDelete Whether delete original file after compress
     * @throws IOException
     */
    public void compressAndGenImage(String imgPath, String outPath, int maxSize, boolean needsDelete) throws IOException {
        compressAndGenImage(getBitmap(imgPath), outPath, maxSize);

        // Delete original file
        if (needsDelete) {
            File file = new File(imgPath);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /**
     * Ratio and generate thumb to the path specified
     *
     * @param image
     * @param outPath
     * @param pixelW  target pixel of width
     * @param pixelH  target pixel of height
     * @throws FileNotFoundException
     */
    public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH) throws FileNotFoundException {
        Bitmap bitmap = ratio(image, pixelW, pixelH);
        storeImage(bitmap, outPath);
    }

    /**
     * Ratio and generate thumb to the path specified
     *
     * @param imgPath
     * @param outPath
     * @param pixelW      target pixel of width
     * @param pixelH      target pixel of height
     * @param needsDelete Whether delete original file after compress
     * @throws FileNotFoundException
     */
    public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH, boolean needsDelete) throws FileNotFoundException {
        Bitmap bitmap = ratio(imgPath, pixelW, pixelH);
        storeImage(bitmap, outPath);

        // Delete original file
        if (needsDelete) {
            File file = new File(imgPath);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /**
     * 添加水印
     * @param src
     * @param watermark
     * @param title
     * @return
     */
    public static Bitmap watermarkBitmap(Bitmap src, Bitmap watermark,
                                         String title) {
        if (src == null) {
            return null;
        }
        int w = src.getWidth();
        int h = src.getHeight();
        //需要處理圖片太大造成的內存超過的問題,這裏我的圖片很小所以不寫相應代碼了
        Bitmap newb= Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);// 創建一個新的和SRC長度寬度一樣的位圖
        Canvas cv = new Canvas(newb);
        cv.drawBitmap(src, 0, 0,null);// 在 0,0座標開始畫入src
        Paint paint=new Paint();
        //加入圖片
        if (watermark != null) {
            int ww = watermark.getWidth();
            int wh = watermark.getHeight();
            paint.setAlpha(50);
            cv.drawBitmap(watermark, w - ww + 5, h - wh + 5, paint);// 在src的右下角畫入水印
        }
        //加入文字
        if(title!=null)
        {
            String familyName ="黑體";
            Typeface font = Typeface.create(familyName,Typeface.NORMAL);
            TextPaint textPaint=new TextPaint();
            textPaint.setColor(Color.RED);
            textPaint.setTypeface(font);
            textPaint.setTextSize(40);
            Log.i("tag","=====title====="+title+"======w-10====="+(w-10)+"==w==="+w+"====h-10======"+(h-10));
            //這裏是自動換行的
            StaticLayout layout = new StaticLayout(title,textPaint,w, Layout.Alignment.ALIGN_OPPOSITE,1.0F,0.0F,true);
            layout.draw(cv);
        }
        cv.save(Canvas.ALL_SAVE_FLAG);// 保存
        cv.restore();// 存儲
        return newb;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章