Android - Any library for adding repost label to bitmap

后端 未结 1 754
被撕碎了的回忆
被撕碎了的回忆 2021-01-29 15:24

I have been trying to make a photo sharing app, with the ability to add your image and name to the image. I have been messing with Canvas for the whole day, but couldn\'t get go

相关标签:
1条回答
  • 2021-01-29 15:56

    if you want to customize it, then instead of solid white rectangle (like in your original code) use a Drawable and the result could be something like this:

    the code:

    // 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;
    }
    
    0 讨论(0)
提交回复
热议问题