gpt4 book ai didi

java - 为 View 的填充着色

转载 作者:行者123 更新时间:2023-12-02 05:47:09 24 4
gpt4 key购买 nike

假设我有 View A,它覆盖了整个屏幕

然后我就这么做了

a.setPadding(90, 0, 90, 0)

现在向下 90 像素,向左 90 像素

我如何为这 90 个像素着色,比如说,红色?

如果我使用 .setBackgroundColour(int color) ,显然它会给整个 View 着色

那我该怎么办?

如果这不可能,是否可以有一个仅红色、90 像素宽并覆盖该填充区域的 View ?但仍然允许触摸事件到达填充区域

我需要以编程方式完成所有这些

最佳答案

您可以创建一个自定义 View ,在填充区域中绘制颜色。在这里,我扩展了 View,但是如果您愿意,您可以扩展其他内容。

package sample.package.name;

public class ColoredPaddingView extends View {
Rect rect = new Rect();

// Constructors omitted. Override them all and call the super constructor

@Override
public void onDraw(Canvas canvas) {
int l = getPaddingLeft();
int t = getPaddingTop();
int r = getWidth() - getPaddingRight();
int b = getHeight() - getPaddingBottom();
rect.set(l, t, r, b);

canvas.save();
canvas.clipRect(rect, Region.Op.DIFFERENCE);
canvas.drawColor(Color.RED); // or some other color
canvas.restore;

super.onDraw(canvas);
}
}

在布局 XML 中,您将使用 View 的完全限定类名(包括包),如下所示:

<sample.package.name.ColoredPaddingView
android:layout_width="..."
android:layout_height="..."
... />

关于java - 为 View 的填充着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23956876/

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