我创建了一个自定义视图,允许我对文本进行描边。 到目前为止它工作得非常好,我目前唯一的问题是它没有包含内容。它实际上似乎填满了整个父母。
我只需要它来包装文本,这样我就可以将其余的设计恢复到创建自定义视图之前的状态。
这是我的班级
public class DrawText extends View {
String text = "blank";
float textSize = 90;
Context context;
public DrawText(Context context, AttributeSet attrs)
{
super(context, attrs);
this.context = context;
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.DrawText, 0, 0);
try{
text = a.getString(R.styleable.DrawText_titleText);
}
finally
{
a.recycle();
}
}
public void setTextSize(float size) {this.textSize = size;}
public void setText(String text) {this.text = text;}
public String getText() {return text;}
@Override
public void draw(Canvas canvas)
{
Typeface font = Typeface.create(Typeface.DEFAULT, Typeface.ITALIC);
TextPaint strokePaint = new TextPaint();
strokePaint.setColor(Color.BLACK);
strokePaint.setTextAlign(Paint.Align.CENTER);
strokePaint.setTextSize(90);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(4);
strokePaint.setDither(true);
strokePaint.setStrokeJoin(Paint.Join.ROUND);
strokePaint.setStrokeCap(Paint.Cap.ROUND);
strokePaint.setAntiAlias(true);
strokePaint.setTypeface(font);
TextPaint textPaint = new TextPaint();
textPaint.setColor(Color.WHITE);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTextSize(90);
textPaint.setTypeface(font);
textPaint.setDither(true);
textPaint.setAntiAlias(true);
textPaint.setShadowLayer(1, 4, 4, Color.BLACK);
StaticLayout mTextLayout = new StaticLayout(text, textPaint, canvas.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, false);
StaticLayout mStrokeLayout = new StaticLayout(text, strokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, false);
int textHeight = (getHeight()/2) - (mTextLayout.getHeight()/2);
int textWidth = (getWidth()/2);
canvas.translate(textWidth, textHeight);
mStrokeLayout.draw(canvas);
mTextLayout.draw(canvas);
super.draw(canvas);
}
}
在我的布局中使用如下。
<com.example.sw_stage.fancomglass.Drawables.DrawText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:titleText="@string/streaming_fromcontacts"
android:layout_toRightOf="@+id/contact_image"
android:id="@+id/contact_name" />
我是新手使用自定义视图,我认为我应该使用onMeasure方法做一些事情,但我无法如何使用它来实现我的目标。