美文网首页Android
Android(Kotlin)如何使得相机蒙版有透明区域?

Android(Kotlin)如何使得相机蒙版有透明区域?

作者: 想看烟花么 | 来源:发表于2021-09-10 16:11 被阅读0次

代码的世界虽逻辑繁华,却又大道至简。

背景:

在我们的开发日常当中,我们会接到这样的需求:实现拍照功能。那实现拍照功能一般情况下,应用的界面一般都会有遮罩层与完全透明的扫描区域。那我们如何实现透明区域呢?
想要解决掏空的问题一般我们能想到两种实现方式:
1.除了透明区域外,其他地方用带mask背景的view去覆盖填充,那未被填充的区域就是透明区域了。但这样会有这样的问题:透明区域需求是圆角白线框描边怎么办?UI会有瑕疵。
2.直接在mask全区域中心挖出一个透明区域。可据UI设计稿完美绘制.
显然,这里要采用第2种方式实现

效果图:

device-2021-09-13-162129.png

思考:

那要实现掏空中心实现区域透明化,该如何实现?这里就需要了解画笔的PorterDuffXfermode知识。关于该知识点可以借鉴这位大佬的blog https://blog.csdn.net/iispring/article/details/50472485,网上也有一堆的学习资料,这里就不再详细说明了。但这里还有一个问题,是我实际开发过程中遇到的:
当我们用PorterDuffXfermode去掏空一块区域时,我们一般的做法都是继承于view自定义view,在ondraw方法里用它,这样大多数情况下没有任何问题,但是在某些机型上会存在兼容性问题,我在机型SM-G935F android 7.0,相机用的CameraX,遇到此现象:想要被掏空区域并没有变透明,却是黑色,设定的想要的蒙版区域蒙版颜色也不见了,却是透明。兼容性问题真让人头大,经多方探索后我参考了这位博客主的实现方式https://cloud.tencent.com/developer/article/1743020,完美的解决了我的问题:
1.使用自定义Drawable
2.画笔颜色不能设置是透明色的

怎么使用:

transparent_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MaskConstraintLayout">
        <attr name="id_scan_area" format="reference" />
        <attr name="corner_radius" format="dimension" />
    </declare-styleable>
</resources>
 <com.patrick.example.MaskConstraintLayout
            android:id="@+id/root_scan_area"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="@color/color_4C000000"
            app:corner_radius="16dp"
            app:id_scan_area="@id/scan_area"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <View
                android:id="@+id/scan_area"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:background="@drawable/transparent_shape"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintDimensionRatio="11:4"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintWidth_percent="0.76" />
</com.patrick.example.MaskConstraintLayout>

实现:

import android.graphics.*
import android.graphics.drawable.Drawable

class TransparentDrawable(innerDrawable: Drawable) : Drawable() {
    private var srcPaint: Paint? = null
    private var srcPath: Path? = null

    private var mInnerDrawable: Drawable? = null

    init {
        mInnerDrawable = innerDrawable
        srcPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        //Important: the color can not be transparent.
        srcPaint?.color = Color.BLACK
    }

    /**
     * @param srcPath
     */
    fun setSrcPath(srcPath: Path?) {
        this.srcPath = srcPath
    }

    override fun draw(canvas: Canvas) {
        mInnerDrawable?.let { innerDrawable ->
            innerDrawable.bounds = bounds
            if (srcPath == null || srcPath?.isEmpty == true) {
                innerDrawable.draw(canvas)
            } else {
                srcPaint?.let {
                    val saveCount = canvas.saveLayer(
                        0f, 0f,
                        bounds.width().toFloat(), bounds.height().toFloat(), it
                    )
                    innerDrawable.draw(canvas)
                    it.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
                    canvas.drawPath(srcPath!!, it)
                    it.xfermode = null
                    canvas.restoreToCount(saveCount)
                }
            }
        }
    }

    override fun setAlpha(alpha: Int) {
        mInnerDrawable?.alpha = alpha
    }

    override fun setColorFilter(colorFilter: ColorFilter?) {
        mInnerDrawable?.colorFilter = colorFilter
    }

    override fun getOpacity(): Int {
        return mInnerDrawable?.opacity ?: -1
    }
}
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout

class MaskConstraintLayout(context: Context, attributes: AttributeSet?) :
    ConstraintLayout(context, attributes) {
    private var mCornerRadius = 0f
    private var mContext: Context? = null
    private var mTransparentDrawable: TransparentDrawable? = null
    private var mIdScanArea: Int = View.NO_ID

    init {
        mContext = context
        val typeArray = context.obtainStyledAttributes(attributes, R.styleable.MaskConstraintLayout)
        mCornerRadius = typeArray.getDimension(
            R.styleable.MaskConstraintLayout_corner_radius,
            dp2Px(16f)
        )
        mIdScanArea = typeArray.getResourceId(R.styleable.MaskConstraintLayout_id_scan_area, -1)
        typeArray.recycle()
        background?.let {
            mTransparentDrawable = TransparentDrawable(it)
            background = mTransparentDrawable
        }
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        resetBackgroundHoleArea()
    }

    private fun resetBackgroundHoleArea() {
        //transparent of scan area.
        val view = findViewById<View>(mIdScanArea)
        view?.let {
            val path = Path()
            path.addRoundRect(
                view.left.toFloat(),
                view.top.toFloat(),
                view.right.toFloat(),
                view.bottom.toFloat(),
                dp2Px(mCornerRadius / 2f),
                dp2Px(mCornerRadius / 2f),
                Path.Direction.CW
            )
            mTransparentDrawable?.setSrcPath(path)
        } ?: kotlin.run {
            Log.e("MaskConstraintLayout", "you must define app:id_scan_area='@id/scan_area' for current view in xml.")
        }
    }

    private fun dp2Px(dipValue: Float) =
        TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, resources.displayMetrics)
}

我也是有底线的,感谢您的耐心。

相关文章

网友评论

    本文标题:Android(Kotlin)如何使得相机蒙版有透明区域?

    本文链接:https://www.haomeiwen.com/subject/rcfnwltx.html