【发布时间】:2021-02-25 05:06:52
【问题描述】:
我正在尝试制作一个如下所示的自定义视图:
点击时它就像一个按钮。我希望波纹效果只覆盖视图的圆角矩形部分,但我正在努力实现这一点。这是波纹现在的样子:
注意波纹是如何一直到达顶部的,而不是在圆角矩形的边缘处停止。这是我第一次制作自定义视图,我完全迷失了。
public class HeaderButton extends androidx.appcompat.widget.AppCompatTextView {
Paint paint;
float scaledUnit;
RectF rectBounds;
String text = "My text";
public HeaderButton(Context context) {
super(context);
init();
}
public HeaderButton(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public HeaderButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
float screenWidthPixel = this.getResources().getDisplayMetrics().widthPixels;
scaledUnit = screenWidthPixel * 0.001f;
rectBounds = new RectF(3 * scaledUnit, 15 * scaledUnit, getWidth() - (3 * scaledUnit), getHeight() - (3 * scaledUnit));
}
private void init() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
float[] outerRadii = new float[8];
Arrays.fill(outerRadii, 7 * scaledUnit);
RoundRectShape shape = new RoundRectShape(outerRadii, null, null);
ShapeDrawable mask = new ShapeDrawable(shape);
ColorStateList stateList = ColorStateList.valueOf(ContextCompat.getColor(getContext(), R.color.colorError));
setBackgroundDrawable(new RippleDrawable(stateList, null, mask));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float textWidth = paint.measureText(text);
float textStart = Math.round(getWidth() / 2.) - (textWidth / 2);
float textEnd = Math.round(getWidth() / 2.) + (textWidth / 2);
paint.setStyle(Paint.Style.FILL);
int scaledTextSize = getResources().getDimensionPixelSize(R.dimen.header_button_label_text_size);
paint.setTextSize(scaledTextSize);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#777777"));
paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
canvas.drawText(text, Math.round(getWidth() / 2.) - (textWidth / 2), 24 * scaledUnit, paint);
// Removes the portion of the rounded rectangle that's behind the text.
canvas.clipRect(textStart - (10 * scaledUnit), 0, textEnd + (10 * scaledUnit), 20, Region.Op.DIFFERENCE);
paint.setColor(getResources().getColor(R.color.colorMainActivityBottomButtonBorderBackground));
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3 * scaledUnit);
canvas.drawRoundRect(rectBounds, 7 * scaledUnit, 7 * scaledUnit, paint);
}
}
【问题讨论】:
标签: android android-custom-view