其他分享
首页 > 其他分享> > Android开发绘制白色Bitmap显示却是黑的而其他颜色显示正常的解决方法

Android开发绘制白色Bitmap显示却是黑的而其他颜色显示正常的解决方法

作者:互联网

Android开发绘制白色Bitmap显示却是黑的而其他颜色显示正常的解决方法

//实现绘制白色Bitmap的代码如下:
public class DrawView extends View {
    private Bitmap bitmap;
    private Paint paint;

    public DrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        paint = new Paint(Paint.DITHER_FLAG);
        paint.setColor(Color.WHITE);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        bitmap = createBitmap(getMeasuredWidth(), getMeasuredHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(bitmap, 0, 0, paint);
    }

    private Bitmap createBitmap(int width, int height) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.eraseColor(Color.WHITE);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, null, new Rect(0, 0, width, height), paint);
        return bitmap;
    }
}

经过各种排查和测试验证,终于找到原因竟然是手机开启深色模式的锅。。。白色嘛,想想开启深色模式有影响也是有道理的,那居然知道原因了,那就只能让app不跟随系统深色模式了,解决方法如下:

//解决问题之后的代码如下:
public class DrawView extends View {
    private Bitmap bitmap;
    private Paint paint;

    public DrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        paint = new Paint(Paint.DITHER_FLAG);
        paint.setColor(Color.WHITE);
        //新增下面三行代码,让app不跟随系统进入深色模式,这样就可以解决问题了
        //如果不想代码里设置,也可以在themes.xml文件里设置style主题为Light样式的
        //并且添加<item name="android:forceDarkAllowed" tools:targetApi="q">false</item>
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            setForceDarkAllowed(false);
        }
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        bitmap = createBitmap(getMeasuredWidth(), getMeasuredHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(bitmap, 0, 0, paint);
    }

    private Bitmap createBitmap(int width, int height) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.eraseColor(Color.WHITE);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, null, new Rect(0, 0, width, height), paint);
        return bitmap;
    }
}

标签:显示,int,canvas,bitmap,paint,Android,Bitmap,Canvas
来源: https://www.cnblogs.com/yongfengnice/p/16477037.html