gpt4 book ai didi

android - 自定义TextView传数据给onDraw

转载 作者:行者123 更新时间:2023-11-29 17:43:55 25 4
gpt4 key购买 nike

我需要做自定义 TextView(带边框效果的文本)。我有如下代码。

public class BorderTextView extends TextView {

private int textSize;
private String strokeColor;
private String textColor;
private String text;
private Canvas canvas;

public BorderTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public String getMyStrokeColor() {
return strokeColor;
}

public String getMyTextColor() {
return textColor;
}

public String getMyText() {
return text;
}

public int getMyTextSize() {
return textSize;
}

public void setParameters(String strokeColor, String textColor, String text, int textSize) {
this.textSize = textSize;
this.strokeColor = strokeColor;
this.textColor = textColor;
this.text = text;
}


@Override
protected void onDraw(Canvas canvas) {

if (getMyStrokeColor() != null) {
Paint paint = new Paint();
paint.setColor(Color.parseColor(getMyStrokeColor()));
paint.setTextSize(getMyTextSize());
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(getTextSize() / 5);
paint.setAntiAlias(true);
paint.setTextAlign(Paint.Align.CENTER);

int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() +
paint.ascent()) / 2));

canvas.drawText(getMyText(), xPos, yPos, paint);

paint.setStrokeWidth(0f);
paint.setColor(Color.parseColor(getMyTextColor()));
paint.setTextSize(getMyTextSize());

canvas.drawText(getMyText(), xPos, yPos, paint);
}
}

}

在 XML 中:

                <com.app.widget.BorderTextView
android:id="@+id/category"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:gravity="center" />

在 Activity 中:

private BorderTextView category;
category = (BorderTextView) rootView.findViewById(R.id.category);

category = new BorderTextView(getActivity(), null);
category.setParameters("#000000", firstColor, secondColor, 60);

如何将这 4 个值传递到我的自定义 TextView ?因为我上面的代码不起作用。

它不起作用,因为我的值为空。

最佳答案

您正在将 category 初始化为布局中定义的 BorderTextView,但随后您正在实例化 BorderTextView 的新实例并分配它到类别。您在其上调用 setParameters() 的实例不是屏幕上的实例,因此也不是正在绘制的实例。删除行:

category = new BorderTextView(getActivity(), null);

关于android - 自定义TextView传数据给onDraw,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27733861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com