Android 如何在画布后面设置CustomView的背景?
我有一个自定义的Android 如何在画布后面设置CustomView的背景?,android,canvas,background,android-custom-view,Android,Canvas,Background,Android Custom View,我有一个自定义的视图,如下所示: public class ShadowTextView extends TextView { ... @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int parentWi
视图
,如下所示:
public class ShadowTextView extends TextView {
...
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
final int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
final int minSize = Math.min(parentWidth, parentHeight);
mShadow = new Paint(Paint.ANTI_ALIAS_FLAG);
RadialGradient gradient = new RadialGradient(
parentWidth * mCenterX,
parentHeight * mCenterY,
minSize * mGradientRadiusWidthPercent,
new int[]{mStartColor, mCenterColor, mEndColor},
null,
android.graphics.Shader.TileMode.CLAMP);
mShadow.setDither(true);
mShadow.setShader(gradient);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(0, 0, getWidth(), getHeight(), mShadow);
}
...
}
在XML中,我想在我的画布上的背景中使用这个CustomView
<com.ShadowTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/circle"
android:paddingBottom="3dp"
android:gravity="center"
android:text="+"
android:textColor="@android:color/white"
android:textSize="32dp"
app:startColor="@android:color/black"
app:centerColor="@android:color/black"
app:endColor="@android:color/transparent"
app:gradientRadiusWidthPercent=".5"
/>
circle.xml文件:
<layer-list>
<item xmlns:android="http://schemas.android.com/apk/res/android"
android:bottom="6dp"
android:left="3dp"
android:right="3dp">
<shape android:shape="oval">
<!--
accentColor might be material red #F44336
-->
<solid android:color="#F44336" />
</shape>
</item>
</layer-list>
Canvas
阴影在前景中,但应该在背景中,这意味着在android:background=“@drawable/circly”
和文本后面
目前的结果是:
希望的结果是:
最后一个重要提示:
我知道有很多开放库可以获得浮动操作按钮。请不要介绍我。我想找到我自己的解决方案,所以设计一个文本视图。解决方案非常简单。XML定义的背景设置“android\u background
”是在draw(…)
方法中绘制的,而不是在onDraw(…)
方法中绘制的
因此,我所要做的就是在draw(…)
方法中绘制阴影,然后调用super.draw(…)
方法绘制背景(在阴影上)
此外,在super.draw(…)
方法中,调用onDraw(…)
方法来绘制TextView
的文本
与上述代码相同,但有一点变化:
public class ShadowTextView extends TextView {
...
// overriding of the draw() method instead of the onDraw(...) method
@Override
public void draw(Canvas canvas) {
canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), mShadow);
/*
Draw the background setting by XML definition android:background
*/
super.draw(canvas);
}
...
}
感谢您的关注。“android:background”(顾名思义)放在背景上,但您可以通过调用getBackground()来绘制背景,这很笨拙,但可能存在陷阱:不要在构造函数中调用“setBackground”:/