我已经设法创建了一个可以在文本周围创建非常漂亮的平滑笔触的绘画。但是我很难将它绘制到我需要的地方,主要是我相信我正在扩展View而不是TextView?
我的目标是能够在我想要的布局上找到任何文字。
DrawView.java
public class DrawView extends View{
Paint paint = new Paint();
String text = "Blank";
public DrawView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DrawView(Context context) {
super(context);
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void draw(Canvas canvas ) {
Paint strokePaint = new Paint();
strokePaint.setARGB(255, 0, 0, 0);
strokePaint.setTextSize(28);
//strokePaint.setTypeface(tf);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeJoin(Paint.Join.ROUND);
strokePaint.setStrokeCap(Paint.Cap.ROUND);
strokePaint.setStrokeWidth(9);
strokePaint.setAntiAlias(true);
Paint textPaint = new Paint();
textPaint.setARGB(255, 255, 255, 255);
textPaint.setTextSize(28);
//textPaint.setTypeface(tf);
textPaint.setAntiAlias(true);
canvas.drawText(text, 99, 99, strokePaint);
canvas.drawText(text, 99, 101, strokePaint);
canvas.drawText(text, 101, 99, strokePaint);
canvas.drawText(text, 101, 101, strokePaint);
canvas.drawText(text, 100, 100, textPaint);
super.draw(canvas);
}
}
XML
<com.shadow.pets.DrawView
android:id="@+id/energyText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
此视图会覆盖我的整个LinearLayout,而我无法控制它绘制的位置?如果我扩展TextView,我根本无法使用它!
很抱歉,如果它令人困惑,我知道我必须脱轨,但已经尝试了几个小时而且找不到这些话让它更清楚了!
答案 0 :(得分:1)
我认为现在的问题是,你的DrawView并不“知道”它有多大,所以Wrap_content只占用了所有可用空间。你可以通过重写onMeasure()来解决这个问题。你可能想要像这样包装你的文字大小:
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int padding = 10;
Rect r = new Rect();
Paint p = new Paint();;
p.setTextSize(28);
p.getTextBounds(text, 0, text.length(), r);
this.setMeasuredDimension(r.right - r.left + padding,
r.bottom - r.top + padding);
}
“填充”是为笔划边框添加额外的大小。然后在绘图类中,将drawTexts更改为:
int padding = 5;
int x = this.getLeft() + padding;
int y = this.getBottom() - padding;
canvas.drawText(text, x - 1, y - 1, strokePaint);
canvas.drawText(text, x - 1, y + 1, strokePaint);
canvas.drawText(text, x + 1, y - 1, strokePaint);
canvas.drawText(text, x + 1, y + 1, strokePaint);
canvas.drawText(text, x, y, textPaint);
理论上这应该有用。当我尝试它时,只要DrawView是LinearLayout中最左侧的视图,它看起来很棒,但是当有TextView然后是DrawView时它被部分覆盖。我不确定为什么:(但我希望这有助于你开始!