我在ImageView上有2个TextView。我正在使用Canvas
和Paint
类来绘制图片上的标题。我希望字幕在图像顶部和TextView顶部之间有大约20dp的间隙。有什么方法可以将这些值输入Canvas.drawText()
的y值?
文本原点就像图像一样,它从左上角开始,对于顶部文本,只需将y原点设置为+ 20dp,对于底部文本,将y原点设置为text.height + 20dp
中心文字:
x = image.width/2 - text.width/2;
顶部文字Y轴
y = 20;
底部文字Y轴:
y = image.height - 20 - text.height;
在尝试获取绘制文本的宽度之前测量文本很重要。
检查这个答案:Measuring text height to be drawn on Canvas ( Android )
你可以点这个链接https://developer.android.com/training/custom-views/custom-drawing#java。它包含定位的详细说明。在你的情况下,
你需要先创建你的文字
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(textColor);
if (textHeight == 0) {
textHeight = textPaint.getTextSize();
} else {
textPaint.setTextSize(textHeight);
}
piePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
piePaint.setStyle(Paint.Style.FILL);
piePaint.setTextSize(textHeight);
shadowPaint = new Paint(0);
shadowPaint.setColor(0xff101010);
shadowPaint.setMaskFilter(new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL));
像这样,您需要设置填充并将其放在您想要的位置如下
// Account for padding
float xpad = (float)(getPaddingLeft() + getPaddingRight());
float ypad = (float)(getPaddingTop() + getPaddingBottom());
// Account for the label
if (showText) xpad += textWidth;
float ww = (float)w - xpad;
float hh = (float)h - ypad;
// Figure out how big we can make the pie.
float diameter = Math.min(ww, hh);
我从上面提到的URL获得了这整个代码。
你需要在下面添加代码来定位中心
Paint yourPaint = new Paint();
int xP = (canvas.getWidth() / 2);
int yP = (int) ((canvas.getHeight() / 2) - ((yourPaint .descent()yourPaint .ascent()) / 2)) ;
canvas.drawText(yourTextView, xP, yP, yourPaint);