在我的应用程序中,我需要使用位图和drawCircle()方法绘制圆圈.
一切都运行正常,直到Android 6.0.
它仍然在所有以前的版本上绘制圆圈,但在6.0上使用应用程序时绘制矩形.但是,如果我将其更改为填充,则会在api 22和api 23中绘制一个圆圈.
任何人都有同样的问题或任何想法为什么会这样?
这是源代码和屏幕截图(左侧是API 23上运行的应用程序,右侧是API 22). same app on different api’s
public final class Circle1View extends View { private float xCenter,yCenter; private Bitmap grid = null; public Circle1View (Context context) { super(context); init(); } private void init() { setLayerType(View.LAYER_TYPE_SOFTWARE,null); } @Override protected void onDraw(Canvas canvas) { int w = getWidth(); int h = getHeight(); xCenter = w / 2; yCenter = h / 2; drawBitmaps(w,h); canvas.translate(xCenter,yCenter); canvas.scale(xCenter,yCenter); canvas.drawBitmap(grid,null,new RectF(-1,-1,1,1),null); } private void drawBitmaps(int w,int h) { grid = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(); canvas.translate(xCenter,yCenter); Paint gridPaint = new Paint(); gridPaint.setStrokeWidth(0.01f); // Works with FILL // gridPaint.setStyle(Paint.Style.FILL); gridPaint.setStyle(Paint.Style.STROKE); canvas.setBitmap(grid); canvas.drawCircle(0,0.5f,gridPaint); } }
解决方法
我认为这与你做的缩放和翻译有关.想象一下,绘制的圆是如此之小,它只需要4个像素.将其放大到最大尺寸时,在这些像素之间留下4条直线.
当我将笔划宽度更改为0.04f时,问题就消失了.我建议您直接使用提供的Canvas来简化代码:
@Override protected void onDraw(Canvas canvas) { int w = getWidth(); int h = getHeight(); xCenter = w / 2; yCenter = h / 2; Paint gridPaint = new Paint(); gridPaint.setStrokeWidth(1f); gridPaint.setStyle(Paint.Style.STROKE); canvas.drawCircle(xCenter,yCenter,w/4,gridPaint); }
关于API级别之间差异的问题:Marshmallow引入了drawBitmap()的更改.您可以查看Lollipop和Marshmallow的相应源代码.