要解决在Android 10上渐变颜色可绘制对象无法正常工作(旋转90度)的问题,可以尝试以下解决方法:
public class CustomView extends View {
private Paint mPaint;
public CustomView(Context context) {
super(context);
init();
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
Shader shader = new LinearGradient(0, 0, 0, getHeight(), Color.RED, Color.BLUE, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
}
}
public class CustomView extends View {
private GradientDrawable mDrawable;
public CustomView(Context context) {
super(context);
init();
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
int[] colors = {Color.RED, Color.BLUE};
mDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 获取视图的旋转角度
int rotation = (int) getRotation();
int degrees = rotation % 360;
// 根据旋转角度调整渐变方向
GradientDrawable.Orientation orientation;
if (degrees == 0 || degrees == 180) {
orientation = GradientDrawable.Orientation.TOP_BOTTOM;
} else {
orientation = GradientDrawable.Orientation.LEFT_RIGHT;
}
mDrawable.setOrientation(orientation);
// 绘制渐变颜色可绘制对象
mDrawable.setBounds(0, 0, getWidth(), getHeight());
mDrawable.draw(canvas);
}
}
这些方法可以在Android 10上解决渐变颜色可绘制对象无法正常工作的问题(旋转90度)。根据你的需求和代码结构选择适合的方法来解决问题。