在Android中调整水印位图的大小并重新定位

时间:2016-07-21 14:51:52

标签: android

我正在使用以下方法在现有位图的顶部添加水印徽标:

private Bitmap addWaterMark(Bitmap src) {
        int w = src.getWidth();
        int h = src.getHeight();
        Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(src, 0, 0, null);

        Bitmap waterMark = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.menu_logo);
        canvas.drawBitmap(waterMark, 0, 0, null);

        return result;
    }

如何修改上面的代码,将水印放在位图的右下角,并使其宽度为位图的33%,同时保持其宽高比?

3 个答案:

答案 0 :(得分:0)

希望这有帮助。

private Bitmap addWaterMark(Bitmap src) {
    int w = src.getWidth();
    int h = src.getHeight();
    Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(src, 0, 0, null);


    float scale = 0.33f;
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);
    matrix.postTranslate(w - w * scale, h - h * scale);

    Bitmap waterMark = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.menu_logo);
    canvas.drawBitmap(waterMark, matrix, null);

    return result;
}

答案 1 :(得分:0)

让我按照我想要的方式工作:

private Bitmap addWaterMark(Bitmap src) {
        int w = src.getWidth();
        int h = src.getHeight();
        Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(src, 0, 0, null);

        int watermarkPadding = 50;
        Bitmap waterMark = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.menu_logo);
        int newWatermarkWidth = w / 3;
        int newWatermarkHeight = (waterMark.getHeight() * newWatermarkWidth) / waterMark.getWidth();
        Bitmap newWatermark = Bitmap.createScaledBitmap(waterMark, newWatermarkWidth, newWatermarkHeight, true);
        canvas.drawBitmap(newWatermark, w - newWatermarkWidth - watermarkPadding, h - newWatermarkHeight - watermarkPadding, null);

        return result;
    }

答案 2 :(得分:0)

您可以使用此library,您可以在XML(视图)中绘制水印并转换为位图并添加原始内容。

 private Bitmap generateWaterMark(Bitmap src) {

    //src is your original image
    WaterMark waterMark = new WaterMark(mContext);
    //return the your original image with watermark added
    return waterMark.getImageWaterMarkFromView(src, R.layout.watermark_all);
}