如何以编程方式在图像外部添加水印?

时间:2019-05-26 13:25:22

标签: android android-imageview android-canvas android-image android-paint

当用户从应用程序中保存图像时,我希望图像下方的水印不在图像上,如图所示。我可以使用以下代码在图像上添加水印,但不能在图像下方添加水印。

 public static Bitmap addWatermark(Resources imageView, Bitmap originalImage) {

    int imageWidth, imageHeight;
    Canvas canvas;
    Paint paint;
    Bitmap resultImage, watermarkImage;
    Matrix matrix;
    float scale;
    RectF rectF;
    imageWidth = originalImage.getWidth();
    imageHeight = originalImage.getHeight();

    // Create the new resultImage
    resultImage = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
    paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG);

    paint.setColor(Color.parseColor("#f00"));

    // Copy the original resultImage into the new one
    canvas = new Canvas(resultImage);
    canvas.drawBitmap(originalImage, 0, 0, paint);

    // Load the watermarkImage
    watermarkImage = BitmapFactory.decodeResource(imageView, R.mipmap.ic_launcher_foreground);

    // Scale the watermarkImage to be approximately 40% of the originalImage image height
    scale = (float) (((float) imageHeight * 0.20) / (float) watermarkImage.getHeight());

    // Create the matrix
    matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Determine the post-scaled size of the watermarkImage
    rectF = new RectF(0, 0, watermarkImage.getWidth(), watermarkImage.getHeight());
    matrix.mapRect(rectF);

    // Move the watermarkImage to the bottom right corner
    matrix.postTranslate(imageWidth - rectF.width(), imageHeight - rectF.height());

    paint.setAlpha(50);

    // Draw the watermarkImage
    canvas.drawBitmap(watermarkImage, matrix, paint);

    // Free up the resultImage memory
    watermarkImage.recycle();

    return resultImage;
}

enter image description here

0 个答案:

没有答案