給圖片添加水印字體

public static Bitmap drawTextToBitmap(Context context, Bitmap bitmap, String... strings) {
        //根據圖片大小和屏幕大小將圖片縮放
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        int screenWidth = metrics.widthPixels;
        int screenHeight = metrics.heightPixels;
        int bitmapWidth = bitmap.getWidth();
        int bitmapHeight = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float widthScale = (float)screenWidth/bitmapWidth; //必定要加上float否則createBitmap的時候會報錯
        float heightScale = (float)screenHeight/bitmapHeight;
        matrix.postScale(widthScale, heightScale);
        Bitmap src = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, true);
        Bitmap result = src.copy(Bitmap.Config.ARGB_8888, true);

        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setTextSize(40);
        paint.setColor(Color.WHITE);
        int textHeight = 0;
        for (int i=0; i<strings.length; i++) {
            String str = strings[i];
            Rect bounds = new Rect();
            paint.getTextBounds(str, 0, str.length(), bounds);
            if (i == 0) {
                textHeight = bounds.height();
            }
            canvas.drawText(str, 20, result.getHeight() - textHeight*(i+1) - 40*(i+1), paint);
        }
        canvas.save();
        canvas.restore();
        bitmap.recycle();
        return result;
    }
相關文章
相關標籤/搜索