Image in ImageView disappear

…衆ロ難τιáo~ 提交于 2021-01-29 02:15:27

问题


In MainActivtiy, we use Glide to load URL image into imgSignature.

When imgSignature clicked, a custom dialog pop out and it will display the image in imgSign. Our problem is when we clicked the done button in the custom dialog, the image inside imgSignature become empty and getting this toast message bgDrawable null.

Why image in imgSignature will gone ?

      lateinit var signDialog: Dialog

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)

            signDialog = Util().dialogSignature(getActivity())

            var mSignature = signature(activity, null)
            signDialog.relativeLayout2.addView(mSignature)

            var image: Bitmap? = null

            if (obj?.signature_image?.url != null) {
                Glide.with(activity)
                    .load(obj?.signature_image?.url.toString())
                    .into(imgSignature)
            }

            imgSignature.setOnClickListener {
                signDialog.show()
                if (obj?.signature_image?.url != " ") {
                    Glide.with(activity)
                        .load(obj?.signature_image?.url.toString())
                        .into(signDialog.imgSign);
                }
            }

            signDialog.doneTxt.setOnClickListener {
                signDialog.dismiss()
                imgSignature.setImageBitmap(getBitmapFromView(mSignature))
            }
    }

 fun getBitmapFromView(view: View): Bitmap {
        //Define a bitmap with the same size as the view
        val returnedBitmap = Bitmap.createBitmap(250, 250, Bitmap.Config.ARGB_8888)
        //Bind a canvas to it
        val canvas = Canvas(returnedBitmap)
        //Get the view's background
        val bgDrawable = view.background
        if (bgDrawable != null) {
            longToast("bgDrawable not null")
            //has background drawable, then draw it on the canvas
            bgDrawable.draw(canvas)
        }
        else {
            //does not have background drawable, then draw white background on the canvas
            canvas.drawColor(Color.WHITE)
            // draw the view on the canvas
            view.draw(canvas)
            longToast("bgDrawable null")
        }
        //return the bitmap
        return returnedBitmap
    }
}

Util

 fun dialogSignature(context: Context?):Dialog{

        var dialog = Dialog(context)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(R.layout.dialog_signature)
        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        return dialog
    }

dialog_signature

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                             xmlns:app="http://schemas.android.com/apk/res-auto"
                                             xmlns:tools="http://schemas.android.com/tools"
                                             android:id="@+id/relativeLayout1"
                                             android:layout_width="match_parent"
                                             android:layout_height="230dp"
                                             android:orientation="vertical"
                                             android:background="@android:color/white">

    <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content"
                  android:background="@color/colorPrimaryShadow"
                  android:orientation="horizontal"
                  android:id="@+id/linearLayout1"
                  android:gravity="center"
                  android:layout_marginBottom="2dp" app:layout_constraintEnd_toEndOf="parent"
                  app:layout_constraintBottom_toTopOf="@+id/relativeLayout2" app:layout_constraintTop_toTopOf="parent"
                  app:layout_constraintStart_toStartOf="parent">

        <TextView
                android:layout_marginLeft="10dp"
                android:layout_weight="0.4"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="Place Signature"
                android:textSize="17sp"
                android:layout_gravity="right"/>

        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
                  android:layout_marginRight="10dp"
                  android:id="@+id/doneTxt"
                  android:text="Done"
                  android:textColor="@color/colorDarkBlue"/>

    </LinearLayout>

    <RelativeLayout android:layout_width="0dp" android:layout_height="0dp"
                    android:id="@+id/relativeLayout2"
                    android:background="@color/colorWhite"
                    app:layout_constraintTop_toBottomOf="@+id/linearLayout1" app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent" app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintHorizontal_bias="1.0">

        <ImageView android:layout_width="match_parent" android:layout_height="match_parent"
                   android:id="@+id/imgSign"/>
    </RelativeLayout>


    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
              android:layout_below="@+id/linearLayout1"
              android:textColor="@color/colorDarkBlue"
              android:text="Clear" app:layout_constraintStart_toStartOf="parent"
              android:layout_marginStart="8dp" app:layout_constraintEnd_toEndOf="parent"
              android:layout_marginEnd="8dp" app:layout_constraintHorizontal_bias="1.0"
              android:layout_marginBottom="16dp" app:layout_constraintBottom_toBottomOf="parent"
              android:id="@+id/clearTxt"/>

</android.support.constraint.ConstraintLayout>

Happy chinese new year to all chinese

Edit

I tried @rafa answer, but get this exception

cannot be cast to android.widget.ImageView  

on line

val bgDrawable = (view as ImageView).drawable

signture

inner class signature(context: Context, attrs: AttributeSet?) : View(context, attrs) {
        private val paint = Paint()
        private val path = Path()

        private var lastTouchX: Float = 0.toFloat()
        private var lastTouchY: Float = 0.toFloat()
        private val dirtyRect = RectF()

        private val STROKE_WIDTH = 5f
        private val HALF_STROKE_WIDTH = STROKE_WIDTH / 2

        init {
            paint.setAntiAlias(true)
            paint.setColor(Color.BLACK)
            paint.setStyle(Paint.Style.STROKE)
            paint.setStrokeJoin(Paint.Join.ROUND)
            paint.setStrokeWidth(STROKE_WIDTH)
        }

        override fun onDraw(canvas: Canvas) {
            canvas.drawPath(path, paint)
        }

        override fun onTouchEvent(event: MotionEvent): Boolean {
            val eventX = event.x
            val eventY = event.y
//            mGetSign.setEnabled(true)

            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    path.moveTo(eventX, eventY)
                    lastTouchX = eventX
                    lastTouchY = eventY
                    return true
                }

                MotionEvent.ACTION_MOVE,

                MotionEvent.ACTION_UP -> {
                    resetDirtyRect(eventX, eventY)
                    val historySize = event.historySize
                    for (i in 0 until historySize) {
                        val historicalX = event.getHistoricalX(i)
                        val historicalY = event.getHistoricalY(i)
                        expandDirtyRect(historicalX, historicalY)
                        path.lineTo(historicalX, historicalY)
                    }
                    path.lineTo(eventX, eventY)
                }
                else -> {
                    debug("Ignored touch event: $event")
                    return false
                }
            }

            invalidate(
                (dirtyRect.left - HALF_STROKE_WIDTH).toInt(),
                (dirtyRect.top - HALF_STROKE_WIDTH).toInt(),
                (dirtyRect.right + HALF_STROKE_WIDTH).toInt(),
                (dirtyRect.bottom + HALF_STROKE_WIDTH).toInt()
            )

            lastTouchX = eventX
            lastTouchY = eventY

            return true
        }

        private fun debug(string: String) {
//            Log.v("log_tag", string)
        }

        private fun expandDirtyRect(historicalX: Float, historicalY: Float) {
            if (historicalX < dirtyRect.left) {
                dirtyRect.left = historicalX
            } else if (historicalX > dirtyRect.right) {
                dirtyRect.right = historicalX
            }

            if (historicalY < dirtyRect.top) {
                dirtyRect.top = historicalY
            } else if (historicalY > dirtyRect.bottom) {
                dirtyRect.bottom = historicalY
            }
        }

        private fun resetDirtyRect(eventX: Float, eventY: Float) {
            dirtyRect.left = Math.min(lastTouchX, eventX)
            dirtyRect.right = Math.max(lastTouchX, eventX)
            dirtyRect.top = Math.min(lastTouchY, eventY)
            dirtyRect.bottom = Math.max(lastTouchY, eventY)
        }

    }

回答1:


First of all, your mSignature doesnot hold any Image, so returns null when you try to retrieve Image( or background) from it. Removing the mSignature with imgSignature should work. But still am not sure why you need signature class.

lateinit var signDialog: Dialog

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        signDialog = Util().dialogSignature(getActivity())

        //var mSignature = signature(activity, null)
        //signDialog.relativeLayout2.addView(mSignature)

        var image: Bitmap? = null

        if (obj?.signature_image?.url != null) {
            Glide.with(activity)
                .load(obj?.signature_image?.url.toString())
                .into(imgSignature)
        }

        imgSignature.setOnClickListener {
            signDialog.show()
            if (obj?.signature_image?.url != " ") {
                Glide.with(activity)
                    .load(obj?.signature_image?.url.toString())
                    .into(signDialog.imgSign);
            }
        }

        signDialog.doneTxt.setOnClickListener {
            signDialog.dismiss()



            // code change goes here imgSignature
            imgSignature.setImageBitmap(getBitmapFromView(imgSignature))
        }
}

You are using view.background instead of view.drawable as Imageview is set with src attribute by glide. And you have to setBounds for the drawable. Please find the changes below.

fun getBitmapFromView(view: View): Bitmap {
        //Define a bitmap with the same size as the view
        val returnedBitmap = Bitmap.createBitmap(250, 250, Bitmap.Config.ARGB_8888)
        //Bind a canvas to it
        val canvas = Canvas(returnedBitmap)


        //Get the Imageview's src drawable
        val bgDrawable = (view as ImageView).drawable


        if (bgDrawable != null) {
            bgDrawable.setbounds(10,10,240,240); // setting bounds with padding of 10

            longToast("bgDrawable not null")
            //has background drawable, then draw it on the canvas
            bgDrawable.draw(canvas)
        }
        else {
            //does not have background drawable, then draw white background on the canvas
            canvas.drawColor(Color.WHITE)
            // draw the view on the canvas
            view.draw(canvas)
            longToast("bgDrawable null")
        }
        //return the bitmap
        return returnedBitmap
    }
}

Happy New Year :)



来源:https://stackoverflow.com/questions/54519952/image-in-imageview-disappear

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!