Andorid安卓简单的打水印实例代码

2018-11-27 / 1 阅读 / Android

代码已注释

   //打水印
    private Bitmap drawWatermark(Bitmap src) {
        // 需要打上水印的文字
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.YELLOW);
        textPaint.setTextSize(20);
        textPaint.setTextAlign(Paint.Align.CENTER);//水平居中
        // 测量文字宽度
        float textWidth = textPaint.measureText(date);
        // 测量文字垂直偏移量,文字垂直中心偏上,需要计算着便宜量才能保证文字垂直居中
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        float offset = (Math.abs(fontMetrics.top) - fontMetrics.bottom) / 2;

        int width = src.getWidth();
        int height = src.getHeight();
        Bitmap newBmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(newBmp);
        canvas.drawBitmap(src, 0, 0, null);
        src.recycle();

        int padding = 30;//放在右下角,需要留白尺寸
        canvas.drawText(date, width - textWidth / 2 - padding, height + offset - padding, textPaint);

        return newBmp;
    }
相关推荐