本文介绍了ImageView中的图像消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MainActivtiy中,我们使用Glide将URL图像加载到imgSignature.

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

单击imgSignature时,将弹出一个自定义对话框,它将在imgSign中显示图像.我们的问题是,当单击自定义对话框中的完成按钮时,imgSignature中的图像变为空白,并得到此吐司消息bgDrawable null.

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.

为什么imgSignature中的图像会消失?

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
    }
}

使用

 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
    }

对话签名

<?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>

所有中国人春节快乐

修改

我尝试了@rafa答案,但遇到了这个异常

I tried @rafa answer, but get this exception

cannot be cast to android.widget.ImageView

在线

val bgDrawable = (view as ImageView).drawable

签名

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)
        }

    }

推荐答案

首先,您的mSignature不保存任何图像,因此当您尝试从中获取图像(或背景)时,返回null.使用 imgSignature 删除 mSignature 应该可以.但是仍然不确定为什么需要签名类.

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))
        }
}

您正在使用 view.background 而不是 view.drawable ,因为Imageview是通过src属性设置的.而且您必须为drawable设置setBounds.请在下面找到更改.

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
    }
}

新年快乐:)

这篇关于ImageView中的图像消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 16:43