我想在特定大小的矩形中绘制文本,但我得到的结果并不令人满意。
这是我到目前为止尝试过的代码:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mCanvas = canvas;
parentRect = new Rect();
mCanvas.getClipBounds(parentRect);
maxLeft = parentRect.left;
maxTop = parentRect.top;
maxRight = parentRect.right;
maxBottom = parentRect.bottom;
// custom drawing code here
paint = new Paint();
paint.setStyle(Paint.Style.FILL);
// make the entire canvas white
paint.setColor(Color.GRAY);
canvas.drawPaint(paint);
String txt = getContext().getString(R.string.txt_graphics_rotation);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.BLACK);
paint.setTextSize(50);
paint.setTextAlign(Paint.Align.CENTER);
canvas.save();
canvas.translate(mPosX, mPosY);
canvas.scale(scaleFactor, scaleFactor);
rect = new Rect();
paint.getTextBounds(txt, 0, txt.length(), rect);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
Log.e(TAG, "onDraw: rect : " + rect.left + " : " + rect.top + " : " + rect.right + " : " + rect.bottom);
Paint paint1 = new Paint();
paint1.setColor(Color.BLUE);
paint1.setStrokeWidth(5);
paint1.setStyle(Paint.Style.STROKE);
canvas.save();
TextPaint textPaint = new TextPaint();
textPaint.set(paint);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
StaticLayout staticLayout = StaticLayout.Builder
.obtain(txt, 0, txt.length(), textPaint, parentRect.width())
.setBreakStrategy(Layout.BREAK_STRATEGY_BALANCED)
.setAlignment(Layout.Alignment.ALIGN_NORMAL)
.setIncludePad(true)
.build();
if (staticLayout.getLineCount() == 1) {
widthOfText = textPaint.measureText(txt);
heightOfText = -textPaint.ascent() + textPaint.descent();
} else {
widthOfText = staticLayout.getWidth();
heightOfText = (staticLayout.getHeight());
}
canvas.translate(widthOfText / 2, heightOfText / 2);
staticLayout.draw(canvas);
canvas.drawRect(0, 0, widthOfText, heightOfText, paint1);
canvas.restore();
} else {
canvas.drawText(txt, rect.left, rect.top / 2, paint);
widthOfText = paint.measureText(txt) / 2;
heightOfText = rect.height();
canvas.restore();
}
}
在这里,我将矩形和文本放在不同的位置,但我想合并它们。
注意:我知道我没有遵循最佳实践,请暂时忽略它。