我在 Canvas
对象上使用 LinearGradient
创建渐变。我通过在我的主布局 XML 中包含该类来使用此渐变。
生成梯度的代码是:
public class BackgroundGradient extends View{
private Resources res;
private int [] colors;
private float [] pos;
private Paint paint;
private Shader shader;
public BackgroundGradient(Context context) {
// TODO Auto-generated constructor stub
super(context);
init();
}
public BackgroundGradient(Context context, AttributeSet attrs) {
// TODO Auto-generated constructor stub
super(context,attrs);
init();
}
public BackgroundGradient(Context context, AttributeSet attrs, int defStyle) {
// TODO Auto-generated constructor stub
super(context,attrs,defStyle);
init();
}
private void init() {
paint = new Paint();
res = getResources();
colors = new int[10];
pos = new float[10];
int[] c = { //array of colors };
float[] p = { //positions };
for (int i = 0; i < 8; i++) {
colors[i] = c[i];
pos[i] = p[i];
}
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
shader = new LinearGradient(0,getHeight(),getWidth(), 0, colors, pos, Shader.TileMode.CLAMP);
paint.setShader(shader);
canvas.rotate(20, 0, getHeight());
canvas.drawPaint(paint);
}
}
所以,上面是我在 FrameLayout
中包含在 activity_main.xml
中的文件。
activity_main.xml:
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="@layout/bg_gradient" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#000"
android:orientation="horizontal">
<TextView android:id="@+id/pager_strip"
android:layout_width="100dp"
android:layout_height="5dp"
android:background="@color/mu_blue_6"/>
</LinearLayout>
<!-- other views -->
</FrameLayout>
bg_gradient.xml:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!--
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="This is button" /> -->
<in.mubpack.b2o.ui.BackgroundGradient
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</merge>
我不明白为什么渐变在某些 Android 设备上可见而在其他设备上不可见。谁能帮帮我?
最佳答案
好吧,现在我想我明白了。对我的代码进行了大量调试......我在 LinearGradient
中使用的 colors
和 pos
数组似乎已针对 10 个元素进行了初始化而我只使用了 8 个元素。不知道为什么只有当我开始测试 Ice Cream Sandwich 时才会出现这种情况,但现在已经解决了。我对代码所做的更改:
colors = new int[8];
pos = new float[8];
关于android - 某些 Android 设备中未显示线性渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25112575/