我正在尝试在弧内绘制文本。代码如下
public Round(Context context, int totalSections, int activeSections, String mText) {
super(context);
int dpi = context.getResources().getDisplayMetrics().densityDpi;
float x = 0.25f;
final float radius = x * (new Float(dpi));
mRadius = Math.round(radius) + 20;
mRect = new RectF(
getWidth() + mStrokeWidth, getWidth() + mStrokeWidth, getWidth() + mRadius - mStrokeWidth, getWidth() + mRadius - mStrokeWidth
);
text = mText;
mTotalSections = totalSections;
mActiveSections = activeSections;
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStrokeWidth(mStrokeWidth);
mPaint.setStyle(Paint.Style.STROKE);
mSectionDegree = 360 / mTotalSections;
mSectionDegree -= mGap;
}
public void setmActiveSections(int mActiveSections) {
this.mActiveSections = mActiveSections;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float lastDegree = 270 + (mGap / 2);
for (int i = 0; i < mTotalSections; i++) {
if (i < mActiveSections) {
mPaint.setColor(Color.GREEN);
} else {
mPaint.setColor(Color.GRAY);
}
canvas.drawArc(mRect, lastDegree, mSectionDegree, false, mPaint);
lastDegree += mSectionDegree + mGap;
}
Paint mPaint1 = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint1.setStrokeWidth(1);
mPaint1.setStyle(Paint.Style.STROKE);
mPaint1.setTextSize(15);
mPaint1.setColor(getResources().getColor(R.color.red));
canvas.drawText(text, 20,30, mPaint1);
}
我如何绘制半径为中心的文本...在不同的设备文本上发生的事情不是在半径的中心
在给定的图像中我想要canvas.drawtext应该在Text存在的地方
答案 0 :(得分:3)
将此行添加到onDraw()
mPaint1.setTextAlign(Paint.Align.CENTER);
然后drawText
中的x参数可以只是圆的中心x。您应该可以使用mRect.centerX()
来获取该值。
您也应该使用mRect.centerY()
作为y值,除非需要进行调整。 y参数实际上是文本基线,因此如果要垂直居中以及水平居中,则必须检查绘图FontMetrics
中的某些值,以查看降低y值的程度文本看起来垂直居中。