如何在Bitmap左下角固定位置绘制文本?现有代码居中问题求助
Fix: Draw Text at Fixed Bottom-Left Position on Bitmap
Got it, let's get this sorted! The core issue here is how you're calculating the x and y coordinates—right now they’re set up to center the text, but we can tweak them to reliably pin the text to the bottom-left corner of your bitmap.
Key Coordinate Changes Explained
First, let’s break down why your current code centers the text:
x = (bitmap.getWidth() - bounds.width()) / 2centers horizontally by offsetting half the text width from the bitmap’s midpoint.y = (bitmap.getHeight() + bounds.height()) / 2centers vertically, accounting for Canvas drawing text from its baseline (not the top or bottom of the text itself).
To lock the text to the bottom-left:
- Horizontal position: Use a small left margin instead of centering (so the text doesn’t stick directly to the edge)
- Vertical position: Calculate the correct baseline to ensure the text sits just above the bitmap’s bottom edge, accounting for how fonts render below the baseline (like letters "g" or "y")
Modified Working Code
Here’s the updated method with all the fixes, plus a couple of small improvements for reusability:
public Bitmap drawTextToBitmap(Context gContext, Bitmap bitmap, String gText) { Resources resources = gContext.getResources(); float scale = resources.getDisplayMetrics().density; android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig(); // Fallback to ARGB_8888 if no config exists if (bitmapConfig == null) { bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888; } bitmap = bitmap.copy(bitmapConfig, true); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // Use passed context for resources/assets to make this method reusable paint.setColor(resources.getColor(R.color.fujiColor)); paint.setTypeface(Typeface.createFromAsset(gContext.getAssets(), "fonts/DS-DIGI.TTF")); paint.setTextSize((int) (14 * scale)); paint.setShadowLayer(1f, 0f, 1f, resources.getColor(R.color.fujiShadowColor)); // Get text bounds and font metrics for precise positioning Rect bounds = new Rect(); paint.getTextBounds(gText, 0, gText.length(), bounds); Paint.FontMetrics fontMetrics = paint.getFontMetrics(); // Left position: 4dp margin from the left edge (adjust as needed) int x = (int) (4 * scale); // Bottom position: 4dp margin from the bottom edge, adjusted for font descenders int y = (int) (bitmap.getHeight() - (4 * scale) - fontMetrics.descent); canvas.drawText(gText, x, y, paint); return bitmap; }
Quick Tweaks You Can Make
- If you want the text to stick directly to the left edge, change
x = 0instead of using the 4dp margin. - Adjust the margin values (
4 * scale) to move the text closer to or farther from the edges. - If your font doesn’t have descenders (like a sans-serif without lowercase letters), you could use
bounds.height()instead offontMetrics.descent, butFontMetricsis more reliable for most custom fonts.
内容的提问来源于stack exchange,提问作者user7954210
相关产品推荐
相关产品推荐

