3 回答
TA贡献1817条经验 获得超14个赞
我建议您创建自定义视图,它以圆形的形式呈现视图,并根据我们从布局传递的宽度/高度。它更有活力。
我确实喜欢Son Truong建议的答案,但这似乎不是更通用,因为我们需要硬编码尺寸宽度/高度。
第一步:创建主题style.xml
<declare-styleable name="CircleCompatTextView">
<attr name="cctv_stroke_width" format="dimension" />
<attr name="cctv_background_color" format="color" />
<attr name="cctv_border_color" format="color" />
</declare-styleable>
第 2 步:创建自定义视图。
public class CircleCompatTextView extends AppCompatTextView {
private final Paint paintCircle = new Paint();
private final Paint paintStroke = new Paint();
private final Resources resources;
private int strokeWidth;
private int bgColor;
private int borderColor;
private int cxCy;
public CircleCompatTextView(Context context, AttributeSet attrs) {
super(context, attrs);
resources = context.getResources();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleCompatTextView);
strokeWidth = a.getDimensionPixelSize(R.styleable.CircleCompatTextView_cctv_stroke_width, 1);
bgColor = a.getColor(R.styleable.CircleCompatTextView_cctv_background_color, resources.getColor(android.R.color.transparent));
borderColor = a.getColor(R.styleable.CircleCompatTextView_cctv_border_color, resources.getColor(android.R.color.background_dark));
a.recycle();
init();
}
private void init() {
paintCircle.setColor(bgColor);
paintCircle.setFlags(Paint.ANTI_ALIAS_FLAG);
paintStroke.setColor(borderColor);
paintStroke.setStyle(Paint.Style.STROKE);
paintStroke.setStrokeWidth(strokeWidth);
paintStroke.setFlags(Paint.ANTI_ALIAS_FLAG);
}
@Override
public void draw(Canvas canvas) {
canvas.drawCircle(cxCy, cxCy, cxCy - strokeWidth / 2, paintStroke);
canvas.drawCircle(cxCy, cxCy, cxCy - strokeWidth / 2, paintCircle);
super.draw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
int size = ((height > width) ? height : width);
cxCy = size / 2;
setMeasuredDimension(size, size);
}
}
第三步:自定义视图的使用
<CircleCompatTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center|center_vertical"
android:padding="16dp"
android:textAlignment="center"
app:cctv_background_color="@android:color/transparent"
app:cctv_border_color="@android:color/background_dark"
app:cctv_stroke_width="2dp" />
这是输出
添加回答
举报