Reputation: 1
When I press the button and try to draw a yellow line on SurfaceView, some random mess appears on the screen. How can I access the phone screen the fastest possible way properly to draw lines, rectangles and other basic shapes on it in the app?
I use the code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mylinearlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="MY BUTTON"
android:id="@+id/mybutton"
/>
<SurfaceView
android:id="@+id/mysurfaceview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
tools:context=".MainActivity"/>
</LinearLayout>
and
package com.example.myapp
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.graphics.Color
import android.graphics.Paint
import android.view.SurfaceView
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val sv=findViewById<SurfaceView>(R.id.mysurfaceview)
val b=findViewById<Button>(R.id.mybutton)
b.setOnClickListener() {
val mycanvas=sv.holder.lockCanvas()
val mypaint= Paint()
mypaint.setColor(Color.YELLOW)
mypaint.isAntiAlias=true
mypaint.strokeWidth=5f
mypaint.style=Paint.Style.FILL
mycanvas.drawLine(20f,20f,450f,520f,mypaint)
sv.holder.unlockCanvasAndPost(mycanvas)
}
}
}
which produces this:
Upvotes: 0
Views: 28
Reputation: 10621
You should clear the canvas before drawing.
Either make the background transparent:
mycanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
or use solid color:
mycanvas.drawColor(Color.WHITE)
There is another issue in your code - you are not handling the Surface lifecycle events as described in the docs. This can cause crashes. Consider implementing a custom view class.
Upvotes: 0