我有一个问题,我不知道如何解决。如果可以,请你帮助我。
在我的应用程序中,我必须创建一个自定义视图扩展视图。在此视图中,我应该绘制很多矩形,并通过 canvas.drawRect 或 canvas.drawRoundRect 创建它们。天气晴朗。但我想创建这些矩形的复合设计(带有渐变、角、填充等),并且我想在 XML 中执行这些设置(渐变、角、填充等)。我该怎么做?问题是我在 XML 中确定形状,我只能使用这个可绘制对象作为背景,但是当我绘制矩形时,我无法为矩形设置背景。也许还有另一种方法可以解决问题。我可以使用 XML 形状对象不仅设置为背景,还可以设置具有 x、y 坐标和宽度、高度的视图对象吗?
编辑:
我可以画矩形:
canvas.drawRect(x1, y1, x2, y2, paint);
但我在 XML 中有矩形设置,如下所示:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- Specify a gradient for the background -->
<gradient
android:angle="90"
android:startColor="#55000066"
android:centerColor="#FFFFFF"
android:endColor="#55000066" />
<!-- Specify a dark blue border -->
<stroke
android:width="2dp"
android:color="#000066" />
<!-- Specify the margins that all content inside the drawable must adhere to -->
<padding
android:left="5dp"
android:right="5dp"
android:top="5dp"
android:bottom="5dp" />
<corners
android:topLeftRadius="10dp"
android:topRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp" />
</shape>
我想将此设置应用于我的矩形。如何?
您可以从代码中加载并使用 XML 定义的可绘制对象,如下所示:
public class CustomView extends View {
Drawable shape;
public CustomView(Context context) {
super(context);
shape = context.getResources().getDrawable(R.drawable.shape);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
shape.setBounds(left, top, right, bottom);
shape.draw(canvas)
}
// ... Additional methods omitted for brevity
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)