1

I want to draw a camera focus circle on tap on the PreviewView. So, I wrote some code to draw a circle like below

val sd = ShapeDrawable(OvalShape())
            sd.paint.color = Color.parseColor("#ffffff")
            sd.paint.style = Paint.Style.STROKE
            sd.paint.strokeWidth = 20f

            var img: ImageView = ImageView(this);
            img.background = sd

            val params = FrameLayout.LayoutParams(250, 250)
            params.leftMargin = event.x.toInt() - 125
            params.topMargin = event.y.toInt() - 125

            idFocusIndicator.removeAllViews()
            idFocusIndicator.addView(img, params)

as you can clearly see below how it chopped the sides of the circle on all four sides

enter image description here

I need a clear circle not chopped one ! How to achieve that ?

Vikas Acharya
  • 3,550
  • 4
  • 19
  • 52

2 Answers2

1

This looks like the same issue as the one here. When you create a ShapeDrawable programmatically instead of in XML, it puts the center of your stroke width right at the edges of the canvas, so half your stroke width will be cropped off. If you can't use XML, you can use a LayerList to give your drawable an inset so the edges won't be cropped off.

float strokeWidth = 20f;
val sd = ShapeDrawable(OvalShape()).apply {
    paint.color = Color.parseColor("#ffffff")
    paint.style = Paint.Style.STROKE
    paint.strokeWidth = strokeWidth
}
val layerDrawable = LayerDrawable(arrayOf(sd)).apply {
    val inset = strokeWidth / 2f
    setLayerInset(0, inset, inset, inset, inset)
}
val img: ImageView = ImageView(this)
img.background = layerDrawable 
Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • Great. can you please tell why this behavior was not there in `GradientDrawable`. I thought both are just drawables. – Vikas Acharya Nov 12 '20 at 14:56
  • I think it's probably a bug. ShapeDrawable doesn't behave this way when inflated from XML. I would have expected one of these two classes (ShapeDrawable and GradientDrawable) to extend from the other because they are so similar, but they don't and so some behavior difference has snuck in. – Tenfour04 Nov 12 '20 at 15:32
0

Ok, after some research I replaced ShapeDrawable with GradientDrawable and it's working.

but, I don't know why ShapeDrawable has a problem with it. If anyone knows kindly comment here.

val shape = GradientDrawable()
            shape.setShape(GradientDrawable.OVAL)
            shape.setColor(Color.TRANSPARENT)
            shape.setStroke(20, Color.WHITE)
Vikas Acharya
  • 3,550
  • 4
  • 19
  • 52