Oval shape clipped when created programmatically

后端 未结 5 1969
逝去的感伤
逝去的感伤 2020-12-31 21:16

I\'ve got a clipping problem.

First, I tried to display an oval shape with Xml only. I had the following code:

res/drawable/circle.xml



        
5条回答
  •  情话喂你
    2020-12-31 21:58

    I found the solution on this page: http://www.betaful.com/2012/01/programmatic-shapes-in-android/

    In Android, when you draw with a stroke, it draws the center of the stroke at the boundaries of the shape you are drawing. As you can see, the stroke is getting cropped by the boundaries of the image. Luckily, you can perform transformations on a canvas. What we want to do is transform our stroke shape to be slightly smaller than the boundary – and there’s a Matrix operation for that!

    matrix.setRectToRect(new RectF(0, 0, canvas.getClipBounds().right, canvas.getClipBounds().bottom),
    new RectF(strokeWidth/2, strokeWidth/2, canvas.getClipBounds().right - strokeWidth/2,
        canvas.getClipBounds().bottom - strokeWidth/2),
    Matrix.ScaleToFit.FILL);
    

    Edit

    ... Better and easier solution find in the comment section of the link:

    As you can see in the Android docs, a shape Drawable in resources is actually mapped to a GradientDrawable, not a ShapeDrawable:

    And so, I've got the following code working perfectly:

    GradientDrawable drawable = new GradientDrawable();
    drawable.setColor(Color.TRANSPARENT);
    drawable.setShape(GradientDrawable.OVAL);
    drawable.setStroke((int)dpToPx(2), Color.parseColor("#EEEEEE"));
    drawable.setSize((int)dpToPx(240), (int)dpToPx(240));
    

提交回复
热议问题