Android - 用于将重新发布标签添加到位图的任何库

时间:2017-02-25 15:16:08

标签: android bitmap android-canvas

我一直在尝试制作照片共享应用,能够将图像和名称添加到图像中。我一整天都在使用Canvas,但无法取得好成绩。我能够绘制名称和位图,但它们看起来并不那么好。

这就是为什么我在这里询问是否有任何库或一段代码可以帮助我制作类似[this] [1]的内容。我无法找到任何东西。

编辑:很抱歉没有添加我自己的代码

以下是我最新尝试的代码

import cv2
import os
def def_trimmer(img):
    height, width = img.shape
    img_rev = cv2.bitwise_not(img)
    _, contours, _ = cv2.findContours(img_rev,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
    # contours = np.concatenate(contours, axis = 0)
    # contours = contours[((contours<[20-1, width])|(contours>[height-20-1, -1])).all(axis=(1,2))]
    for outer in contours:  
        # for outer2 in outer1:
        oldlen = len(outer)
        outer = outer[(((outer<[20-1, width])|(outer>[height-20-1, -1])).all(axis=(1, 2)))]
        newlen = len(outer)
        print((oldlen, newlen))
    cv2.drawContours(img,contours,-1,(255,255,255),-1)
    return(img)
img = cv2.imread("img.png")
img_out = def_trimmer(img)
cv2.imshow("out", img_out)

Here is the result

更新 @pskink给了我this code  这很好用

1 个答案:

答案 0 :(得分:1)

如果你想自定义它,那么使用Drawable而不是纯白色矩形(就像在原始代码中一样),结果可能是这样的:

enter image description here

代码:

// for int gravity: see android.view.Gravity, like Gravity.LEFT, Gravity.BOTTOM, etc
// for example:
// Bitmap out = addText(this, in, "Haider Ali Punjabi", android.R.drawable.alert_light_frame, Gravity.BOTTOM, new Point(10, 10));
public Bitmap addText(Context ctx, Bitmap in, String text, int resId, int gravity, Point pad) {
    if (pad == null) pad = new Point();

    Bitmap out = in.copy(Bitmap.Config.ARGB_8888, true);
    Canvas canvas = new Canvas(out);

    Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    textPaint.setColor(Color.BLACK);
    textPaint.setTextAlign(Paint.Align.LEFT);
//    textPaint.setTextSize(128);

    Rect inBounds = new Rect();
    textPaint.getTextBounds(text, 0, text.length(), inBounds);
    float scale = out.getWidth() * 0.35f / inBounds.width();

    Rect container = new Rect(0, 0, out.getWidth(), out.getHeight());
    Rect outBounds = new Rect();
    int w = (int) (inBounds.width() * scale);
    int h = (int) (inBounds.height() * scale);
    Gravity.apply(gravity, 2 * pad.x + w, 2 * pad.y + h, container, outBounds);

    Drawable dr = ctx.getResources().getDrawable(resId);
    Rect padding = new Rect();
    dr.getPadding(padding);
    dr.setBounds(outBounds.left - padding.left, outBounds.top - padding.top, outBounds.right + padding.right, outBounds.bottom + padding.bottom);
    dr.draw(canvas);
    Matrix matrix = new Matrix();
    RectF src = new RectF(inBounds);
    RectF dst = new RectF(outBounds);
    dst.inset(pad.x, pad.y);
    matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
    canvas.concat(matrix);
    canvas.drawText(text, 0, 0, textPaint);
    return out;
}