subclassing SurfaceView and overriding onDraw() to change SurfaceView parameters to generate preview of desired size

蹲街弑〆低调 提交于 2019-12-04 14:35:14

You simply have to add

setWillNotDraw(false)

To the constructor.

And its done..:)

Nishant Shah
public class SelectedRect extends View {
    public SelectedRect(Context context) {
        super(context);     
        bringToFront();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawLine(canvas);
        invalidate();       
        this.bringToFront();    
    }
}

And in activity class :

View rect =  new SelectedRect(this);
rect.bringToFront();
this.addView(rect, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
        LayoutParams.FILL_PARENT));

Something fishy is going on. It seems that you're trying to set the SurfaceView as a preview display. In that case, the Activity should implement SurfaceHolder.Callback (not the SurfaceView). This is so that the Activity can know when the SurfaceView has been created and is ready for drawing. Furthermore, it shouldn't even be necessary to extend SurfaceView: you should be able to user SurfaceView itself.

Assuming I misunderstood and you really want to extend surfaceview for some reason... I don't see where you overrode onDraw in your Preview class. Did you not include this code?

When you say that the onDraw callback tells android 'you don't draw the view. I will draw it since I have been implemented', I disagree. onDraw is a function where a View draws stuff that all views have, such as the background. SurfaceView extends view. When you extend SurfaceView, you can override onDraw to tell android to draw stuff in addition to what the original onDraw in the View draws. In other words, Android always does all the drawing; overriding onDraw just tells it to draw a few more things when it's the right time to draw.

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