【问题标题】:ShapeDrawable to draw circle programatically chopping the sidesShapeDrawable 以编程方式绘制圆切边
【发布时间】:2020-11-12 14:31:12
【问题描述】:

我想在点击PreviewView 时绘制一个相机对焦圈。所以,我写了一些代码来画一个像下面这样的圆圈

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)

你可以在下面清楚地看到它是如何在所有四个边上切掉圆的边

我需要一个没有切碎的清晰圆圈!如何实现?

【问题讨论】:

    标签: java android kotlin android-imageview


    【解决方案1】:

    这看起来与the one here 的问题相同。当您以编程方式而不是在 XML 中创建 ShapeDrawable 时,它​​会将笔划宽度的中心放在画布的边缘,因此您的笔划宽度将被裁剪掉一半。如果你不能使用 XML,你可以使用 LayerList 给你的 drawable 一个插图,这样边缘就不会被裁剪掉。

    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 
    

    【讨论】:

    • 太棒了。你能告诉我为什么GradientDrawable 中没有这种行为吗?我认为两者都只是可绘制的。
    • 我认为这可能是一个错误。当从 XML 膨胀时,ShapeDrawable 不会以这种方式表现。我本来希望这两个类(ShapeDrawable 和 GradientDrawable)中的一个从另一个类扩展,因为它们非常相似,但它们没有,所以一些行为差异已经潜入。
    【解决方案2】:

    好的,经过一番研究,我将 ShapeDrawable 替换为 GradientDrawable 并且它正在工作。

    但是,我不知道为什么ShapeDrawable 有问题。如果有人知道,请在这里评论。

    val shape = GradientDrawable()
                shape.setShape(GradientDrawable.OVAL)
                shape.setColor(Color.TRANSPARENT)
                shape.setStroke(20, Color.WHITE)
    

    【讨论】:

      猜你喜欢
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多