Recent

Author Topic: Slow down drawing  (Read 2267 times)

tango13

  • New Member
  • *
  • Posts: 36
Slow down drawing
« on: April 20, 2022, 10:58:02 pm »
Hi all,
I'm using a jDrawingView to draw some simple graphics and I would like to slow down the drawing a bit.
The drawing code is implemented in the onDraw event and things work as expected.
However, if I try to slow the drawing process by inserting some sleep() the effect is not what I'm looking for, the process actually takes more time but I don't see the drawing progressively made, it's all drawn all at once when the function exits.
Is there a way to achieve what I'm trying to do?

Thanks a lot!

lainz

  • Hero Member
  • *****
  • Posts: 4460
    • https://lainz.github.io/
Re: Slow down drawing
« Reply #1 on: April 21, 2022, 12:30:56 am »
Use a kind of timer, and draw each part of the drawing at specific time?

loaded

  • Hero Member
  • *****
  • Posts: 824
Re: Slow down drawing
« Reply #2 on: April 21, 2022, 07:38:15 am »
In my experience you should use Surfaceview for such drawing operations.

The work I did in this way; https://youtu.be/gBS0AMrJ50s

The relevant example will give you an idea.
Code: Pascal  [Select][+][-]
  1. ....\lazandroidmodulewizard-master\demos\GUI\AppSurfaceViewDemo1
Check out  loaded on Strava
https://www.strava.com/athletes/109391137

Seenkao

  • Hero Member
  • *****
  • Posts: 546
    • New ZenGL.
Re: Slow down drawing
« Reply #3 on: April 21, 2022, 08:10:11 am »
Для понимания происходящего.
Всё что вы рисуете на экране, будет выводится в любом случае сразу.
Для того чтоб добиться эффекта медленной прорисовки, вам надо рисовать по частям, в каждый момент времени добавляя дополнительные примитивы.
Допустим вы хотите вывести квадрат, круг и треугольник, чтоб они появлялись друг за другом. Вы не можете использовать Sleep для этого в одном кадре.
Вам нужно в первом кадре прорисовать квадрат. Во втором кадре прорисовать квадрат и круг. И в третьем кадре прорисовать квадрат, круг и треугольник. Между кадрами соответственно должны быть достаточные промежутки времени, чтоб это было заметно, тут можете использовать Sleep.

google translate:
To understand what is happening.
Everything that you draw on the screen will be displayed in any case immediately.
In order to achieve the effect of slow drawing, you need to draw in parts, adding additional primitives at each point in time.
Let's say you want to draw a square, a circle, and a triangle so that they appear one after the other. You can't use Sleep for this in one frame.
You need to draw a square in the first frame. In the second frame, draw a square and a circle. And in the third frame draw a square, a circle and a triangle. Between frames, respectively, there should be sufficient time intervals for this to be noticeable, here you can use Sleep.
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

loaded

  • Hero Member
  • *****
  • Posts: 824
Re: Slow down drawing
« Reply #4 on: April 21, 2022, 08:31:11 am »
Things are different on Android. Normally, you cannot make any display on the screen before the drawing method is finished.

To understand what is happening.
Everything that you draw on the screen will be displayed in any case immediately.
In order to achieve the effect of slow drawing, you need to draw in parts, adding additional primitives at each point in time.
Let's say you want to draw a square, a circle, and a triangle so that they appear one after the other. You can't use Sleep for this in one frame.
You need to draw a square in the first frame. In the second frame, draw a square and a circle. And in the third frame draw a square, a circle and a triangle. Between frames, respectively, there should be sufficient time intervals for this to be noticeable, here you can use Sleep.
With your method; If you want to draw a drawing containing ~100,000 objects, drawing becomes a nuisance.

But instead;
If you use Surfacaview, which is designed for such work, and a thread owned by surfaceview itself.
Things become very enjoyable.
Check out  loaded on Strava
https://www.strava.com/athletes/109391137

Seenkao

  • Hero Member
  • *****
  • Posts: 546
    • New ZenGL.
Re: Slow down drawing
« Reply #5 on: April 21, 2022, 08:38:54 am »
Вы читаете, что я пишу?
Я написал для понимания, что происходит!!!
Это не метод, это то, как всё это происходит.
Человек в одном кадре пытается сделать задержку. Но это не может быть реализовано в одном кадре. И я ему показываю как должно происходить.

Я не говорю, что ваш метод не правильный! ))) Возможно он его и выберет! Потому что это легче, чем самому что-то реализовывать.

google translate:
Do you read what I write?
I wrote to understand what's going on!!!
It's not a method, it's how it all happens.
A person in one frame is trying to make a delay. But it cannot be implemented in one frame. And I show him how to do it.

I'm not saying your method is wrong! ))) Perhaps he will choose it! Because it's easier than doing something yourself.
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

loaded

  • Hero Member
  • *****
  • Posts: 824
Re: Slow down drawing
« Reply #6 on: April 21, 2022, 09:08:03 am »
I think there is a misunderstanding!

Do you read what I write?
I am a very good reader!

I'm not saying your method is wrong!
I didn't say your method was wrong either. In fact, it's a nice method for drawings with few objects.
But if he wanted to draw with too many objects, he would have to choose a different method.
I wanted to convey this to the relevant friend, not to you.




Check out  loaded on Strava
https://www.strava.com/athletes/109391137

tango13

  • New Member
  • *
  • Posts: 36
Re: Slow down drawing
« Reply #7 on: April 21, 2022, 04:52:55 pm »
Thanks everybody for your suggestions, I'll make some test and let you know.

tango13

  • New Member
  • *
  • Posts: 36
Re: Slow down drawing
« Reply #8 on: April 23, 2022, 09:47:36 am »
Hi all,

I'm trying the SurfaceView use but don't know whether I'm doing things correctly.
I started from the SurfaceView demo skeleton but I'm getting a strange behavior: the DrawInBackground event sometimes gets called with the same "process" value as the previous call and the app crashes.
Am I missing something (probably  :D)?

Thank you

loaded

  • Hero Member
  • *****
  • Posts: 824
Re: Slow down drawing
« Reply #9 on: April 24, 2022, 12:28:54 pm »
previous call and the app crashes.
Yes you are right,
In my project, I used LAMW and Android Studio together, and I modified the Surfaceview component on the Android Studio side. That's why I never faced such a problem.
I think the jSurfaceView.java file needs to be updated in LAMW. I'll try this process to fix the problem when I'm available.

Check out  loaded on Strava
https://www.strava.com/athletes/109391137

tango13

  • New Member
  • *
  • Posts: 36
Re: Slow down drawing
« Reply #10 on: May 04, 2022, 08:28:43 pm »
Thanks for the info.

jmpessoa

  • Hero Member
  • *****
  • Posts: 2297
Re: Slow down drawing
« Reply #11 on: May 04, 2022, 08:36:25 pm »

@loaded
Quote
I modified the Surfaceview component on the Android Studio side. That's why I never faced such a problem.


Please, put here your improved code...


Thanks!
Lamw: Lazarus Android Module Wizard
https://github.com/jmpessoa/lazandroidmodulewizard

loaded

  • Hero Member
  • *****
  • Posts: 824
Re: Slow down drawing
« Reply #12 on: May 05, 2022, 10:05:25 pm »
Master Jmpessoa, sorry for my late reply. I've been very busy these days.

Please, put here your improved code...

First of all, I should point out that this is not enhanced code. It remains child's play next to the examples you make. I just made it to give you an idea.
What I did was;
Code: Pascal  [Select][+][-]
  1. ...\lazandroidmodulewizard-master\android_wizard\smartdesigner\java\jSurfaceView.java

-I replaced the Thread in the  file with Runnabble.

-Then I defined a bitmap as a Buffer for the drawing operations and let the drawing operations be drawn on the screen at desired intervals.

-I converted the SetDrawingInBackgroundSleeptime method directly to the screen refresh method. Don't let the name mislead you.
 


Code: Pascal  [Select][+][-]
  1. package com.example.appsurfaceviewdemo1;
  2.  
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import android.content.Context;
  6. import android.graphics.Bitmap;
  7. import android.graphics.Canvas;
  8. import android.graphics.Paint;
  9. import android.graphics.PixelFormat;
  10. import android.graphics.Rect;
  11. import android.os.AsyncTask;
  12. import android.view.MotionEvent;
  13. import android.view.SurfaceHolder;
  14. import android.view.SurfaceHolder.Callback;
  15. import android.view.SurfaceView;
  16. import android.view.View;
  17. import android.view.ViewGroup;
  18. import android.util.Log;
  19.  
  20.  
  21. /*Draft java code by "Lazarus Android Module Wizard" [6/3/2015 0:43:27]*/
  22. /*https://github.com/jmpessoa/lazandroidmodulewizard*/
  23. /*jVisualControl template*/
  24.  
  25. public class jSurfaceView  extends SurfaceView implements Runnable /*dummy*/ { //please, fix what GUI object will be extended!
  26.  
  27.     private long       pascalObj = 0;    // Pascal Object
  28.     private Controls   controls  = null; // Control Class for events
  29.     private jCommons LAMWCommon;
  30.    
  31.     private Context context = null;
  32.    
  33.     //private OnClickListener onClickListener;   // click event
  34.     private Boolean enabled  = true;           // click-touch enabled!
  35.     private SurfaceHolder surfaceHolder;
  36.     Paint paint;
  37.  
  38.     boolean mRun = false;
  39.     long mSleeptime = 10;
  40.     float mStartProgress = 0;
  41.     float mStepProgress = 1;
  42.     boolean mDrawing = false;
  43.  
  44.     //GUIDELINE: please, preferentially, init all yours params names with "_", ex: int _flag, String _hello ...
  45.  
  46.  
  47.     private Thread drawThread;
  48.         private Bitmap buffer;
  49.         private Canvas bcanvas,scanvas;
  50.        
  51.     public jSurfaceView(Controls _ctrls, long _Self) { //Add more others news "_xxx"p arams if needed!
  52.         super(_ctrls.activity);
  53.         context   = _ctrls.activity;
  54.         pascalObj = _Self;
  55.         controls  = _ctrls;
  56.         LAMWCommon = new jCommons(this,context,pascalObj);
  57.        
  58.         controls.activity.getWindow().setFormat(PixelFormat.UNKNOWN);
  59.  
  60.         surfaceHolder = this.getHolder();
  61.         surfaceHolder.addCallback(new Callback() {
  62.  
  63.             @Override
  64.             public void surfaceCreated(SurfaceHolder holder) {
  65.                 controls.pOnSurfaceViewCreated(pascalObj, holder);
  66.                 //setWillNotDraw(true); //false = Allows us to use invalidate() to call onDraw()
  67.             }
  68.  
  69.             @Override
  70.             public void surfaceChanged(SurfaceHolder holder, int format, int width,  int height) {
  71.                                 buffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  72.                 controls.pOnSurfaceViewChanged(pascalObj,width,height);
  73.             }
  74.  
  75.             @Override
  76.             public void surfaceDestroyed(SurfaceHolder holder) {
  77.                 mRun = false;
  78.             }
  79.         });
  80.      
  81.      /*
  82.      onClickListener = new OnClickListener(){
  83.          public void onClick(View view){  //please, do not remove mask for parse invisibility!
  84.                  if (enabled) {
  85.                     controls.pOnClick(pascalObj, Const.Click_Default); //JNI event onClick!
  86.                  }
  87.               };
  88.      };    
  89.      setOnClickListener(onClickListener);    
  90.      */
  91.  
  92.         paint = new Paint();
  93.  
  94.     } //end constructor
  95.  
  96.     public void jFree() {
  97.         surfaceHolder  = null;
  98.         paint = null;
  99.         LAMWCommon.free();
  100.     }
  101.  
  102.     public void SetViewParent(ViewGroup _viewgroup) {
  103.         LAMWCommon.setParent(_viewgroup);
  104.     }
  105.  
  106.     public void RemoveFromViewParent() {
  107.         LAMWCommon.removeFromViewParent();
  108.     }
  109.  
  110.     public View GetView() {
  111.         return this;
  112.     }
  113.  
  114.     public void SetLParamWidth(int _w) {
  115.         LAMWCommon.setLParamWidth(_w);
  116.     }
  117.  
  118.     public void SetLParamHeight(int _h) {
  119.         LAMWCommon.setLParamHeight(_h);
  120.     }
  121.  
  122.     public void setLGravity(int _g) {
  123.         LAMWCommon.setLGravity(_g);
  124.     }
  125.  
  126.     public void setLWeight(float _w) {
  127.                 LAMWCommon.setLWeight(_w);
  128.     }
  129.  
  130.     public void SetLeftTopRightBottomWidthHeight(int _left, int _top, int _right, int _bottom, int _w, int _h) {
  131.         LAMWCommon.setLeftTopRightBottomWidthHeight(_left,_top,_right,_bottom,_w,_h);
  132.     }
  133.  
  134.     public void AddLParamsAnchorRule(int _rule) {
  135.         LAMWCommon.addLParamsAnchorRule(_rule);
  136.     }
  137.  
  138.     public void AddLParamsParentRule(int _rule) {
  139.         LAMWCommon.addLParamsParentRule(_rule);
  140.     }
  141.  
  142.     public void SetLayoutAll(int _idAnchor) {
  143.         LAMWCommon.setLayoutAll(_idAnchor);
  144.     }
  145.  
  146.     public void ClearLayoutAll() {
  147.         LAMWCommon.clearLayoutAll();
  148.     }
  149.  
  150.  
  151.  
  152.     //write others [public] methods code here......
  153.     //GUIDELINE: please, preferentially, init all yours params names with "_", ex: int _flag, String _hello ...
  154.  
  155.     public void DrawLine(Canvas _canvas, float _x1, float _y1, float _x2, float _y2) {
  156.         _canvas.drawLine(_x1,_y1,_x2,_y2, paint );
  157.     }
  158.  
  159.     public void DrawLine(Canvas _canvas, float[] _points) {
  160.         _canvas.drawLines(_points, paint);
  161.     }
  162.  
  163.     public  void DrawText(Canvas _canvas, String _text, float _x, float _y ) {
  164.         _canvas.drawText(_text,_x,_y,paint);
  165.     }
  166.  
  167.     public  void DrawBitmap(Canvas _canvas, Bitmap _bitmap, int _b, int _l, int _r, int _t) {
  168.         Rect rect = new Rect(_b,_l,_r,_t); //bello, left, right, top
  169.         _canvas.drawBitmap(_bitmap,null,rect,null/*paint*/);
  170.     }
  171.  
  172.     public void DrawBitmap(Canvas _canvas, Bitmap _bitmap , float _left, float _top) {
  173.         _canvas.drawBitmap(_bitmap, _left, _top, null/*paint*/);
  174.     }
  175.  
  176.     public void DrawPoint(Canvas _canvas, float _x1, float _y1) {
  177.         _canvas.drawPoint(_x1,_y1,paint);
  178.     }
  179.  
  180.     public void DrawCircle(Canvas _canvas, float _cx, float _cy, float _radius) {
  181.         _canvas.drawCircle(_cx, _cy, _radius, paint);
  182.     }
  183.  
  184.     public void DrawBackground(Canvas _canvas, int _color) {
  185.         _canvas.drawColor(_color);
  186.     }
  187.  
  188.     public void DrawRect(Canvas _canvas, float _left, float _top, float _right, float _bottom) {
  189.         _canvas.drawRect(_left, _top, _right, _bottom, paint);
  190.     }
  191.  
  192.     public  void SetPaintStrokeWidth(float _width) {
  193.         paint.setStrokeWidth(_width);
  194.     }
  195.  
  196.     public  void SetPaintStyle(int _style) {
  197.         switch (_style) {
  198.             case 0  : { paint.setStyle(Paint.Style.FILL           ); break; }
  199.             case 1  : { paint.setStyle(Paint.Style.FILL_AND_STROKE); break; }
  200.             case 2  : { paint.setStyle(Paint.Style.STROKE);          break; }
  201.             default : { paint.setStyle(Paint.Style.FILL           ); break; }
  202.         }
  203.     }
  204.  
  205.     public  void SetPaintColor(int _color) {
  206.         paint.setColor(_color);
  207.     }
  208.  
  209.     public  void SetPaintTextSize(float _textsize) {
  210.         paint.setTextSize(_textsize);
  211.     }
  212.  
  213.     public void DispatchOnDraw(boolean _value) {
  214.         mDrawing = _value;
  215.         setWillNotDraw(!_value); //false = Allows us to use invalidate() to call onDraw()
  216.     }
  217.  
  218.     public void SaveToFile(String _path, String _filename) {
  219.  
  220.         Bitmap image = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
  221.         Canvas c = new Canvas(image);
  222.         this.draw(c);
  223.         File file = new File (_path +"/"+ _filename);
  224.         if (file.exists ()) file.delete ();
  225.         try {
  226.             FileOutputStream out = new FileOutputStream(file);
  227.  
  228.             if ( _filename.toLowerCase().contains(".jpg") ) image.compress(Bitmap.CompressFormat.JPEG, 90, out);
  229.             if ( _filename.toLowerCase().contains(".png") ) image.compress(Bitmap.CompressFormat.PNG, 100, out);
  230.  
  231.             out.flush();
  232.             out.close();
  233.  
  234.         } catch (Exception e) {
  235.             e.printStackTrace();
  236.         }
  237.     }
  238.  
  239.     @Override
  240.     public  boolean onTouchEvent( MotionEvent event) {
  241.         int act     = event.getAction() & MotionEvent.ACTION_MASK;
  242.         switch(act) {
  243.             case MotionEvent.ACTION_DOWN: {
  244.                 switch (event.getPointerCount()) {
  245.                     case 1 : { controls.pOnSurfaceViewTouch (pascalObj,Const.TouchDown,1,
  246.                             event.getX(0),event.getY(0),0,0); break; }
  247.                     default: { controls.pOnSurfaceViewTouch (pascalObj,Const.TouchDown,2,
  248.                             event.getX(0),event.getY(0),
  249.                             event.getX(1),event.getY(1));     break; }
  250.                 }
  251.                 break;}
  252.             case MotionEvent.ACTION_MOVE: {
  253.                 switch (event.getPointerCount()) {
  254.                     case 1 : { controls.pOnSurfaceViewTouch (pascalObj,Const.TouchMove,1,
  255.                             event.getX(0),event.getY(0),0,0); break; }
  256.                     default: { controls.pOnSurfaceViewTouch (pascalObj,Const.TouchMove,2,
  257.                             event.getX(0),event.getY(0),
  258.                             event.getX(1),event.getY(1));     break; }
  259.                 }
  260.                 break;}
  261.             case MotionEvent.ACTION_UP: {
  262.                 switch (event.getPointerCount()) {
  263.                     case 1 : { controls.pOnSurfaceViewTouch (pascalObj,Const.TouchUp  ,1,
  264.                             event.getX(0),event.getY(0),0,0); break; }
  265.                     default: { controls.pOnSurfaceViewTouch (pascalObj,Const.TouchUp  ,2,
  266.                             event.getX(0),event.getY(0),
  267.                             event.getX(1),event.getY(1));     break; }
  268.                 }
  269.                 break;}
  270.             case MotionEvent.ACTION_POINTER_DOWN: {
  271.                 switch (event.getPointerCount()) {
  272.                     case 1 : { controls.pOnSurfaceViewTouch (pascalObj,Const.TouchDown,1,
  273.                             event.getX(0),event.getY(0),0,0); break; }
  274.                     default: { controls.pOnSurfaceViewTouch (pascalObj,Const.TouchDown,2,
  275.                             event.getX(0),event.getY(0),
  276.                             event.getX(1),event.getY(1));     break; }
  277.                 }
  278.                 break;}
  279.             case MotionEvent.ACTION_POINTER_UP  : {
  280.                 // Log.i("Java","PUp");
  281.                 switch (event.getPointerCount()) {
  282.                     case 1 : { controls.pOnSurfaceViewTouch (pascalObj,Const.TouchUp  ,1,
  283.                             event.getX(0),event.getY(0),0,0); break; }
  284.                     default: { controls.pOnSurfaceViewTouch (pascalObj,Const.TouchUp  ,2,
  285.                             event.getX(0),event.getY(0),
  286.                             event.getX(1),event.getY(1));     break; }
  287.                 }
  288.                 break;}
  289.         }
  290.         return true;
  291.     }
  292.  
  293.     public void SetHolderFixedSize(int _width, int _height) {
  294.         surfaceHolder.setFixedSize(_width, _height);
  295.     }
  296.  
  297.     public Canvas GetLockedCanvas() {
  298.         return surfaceHolder.lockCanvas();
  299.     }
  300.  
  301.     public void UnLockCanvas(Canvas _canvas) {
  302.         if(_canvas != null) {
  303.             surfaceHolder.unlockCanvasAndPost(_canvas);
  304.         }
  305.     }
  306.  
  307.     //invalidate(): This must be called from a UI thread.
  308.     //To call from a non-UI thread, call  postInvalidate().
  309.  
  310.     //http://blog-en.openalfa.com/how-to-draw-graphics-in-android
  311.     //http://blog.danielnadeau.io/2012/01/android-canvas-beginners-tutorial.html         
  312.     //http://www.edu4java.com/en/androidgame/androidgame3.html
  313.  
  314.  
  315.  
  316.  
  317.     public void PostInvalidate() {
  318.         this.postInvalidate();
  319.     }
  320.  
  321.     public void Invalidate() {
  322.         this.invalidate();
  323.     }
  324.  
  325.     public void SetKeepScreenOn(boolean _value) {
  326.         surfaceHolder.setKeepScreenOn(_value);
  327.     }
  328.  
  329.     //Set whether this view can receive the focus.
  330.     //Setting this to false will also ensure that this view is not focusable in touch mode.
  331.     public void SetFocusable(boolean _value) {
  332.         this.setFocusable(_value); // make sure we get key events
  333.     }
  334.  
  335.     public void SetProgress(float _startValue, float _step) {
  336.         mStartProgress = _startValue;
  337.         mStepProgress =  _step;
  338.     }
  339.  
  340.  
  341.     public void DoDrawingInBackground(boolean _value) {
  342.         if (!mRun) {
  343.             setWillNotDraw(!_value);
  344.                         mRun = _value;
  345.                         drawThread = new Thread(this, "Draw thread");
  346.                         drawThread.start();    
  347.         }              
  348.     }
  349.  
  350.     @Override
  351.     protected void onDraw(Canvas canvas) {
  352.                         buffer = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
  353.                         bcanvas = new Canvas(buffer);
  354.                     bcanvas.drawColor(0xFFFFFFFF);
  355.  
  356.                     Log.i("* SurfaceView onDraw",this.getWidth()+ "x" + this.getHeight());
  357.                         controls.pOnSurfaceViewDraw(pascalObj, bcanvas);
  358.     }
  359.  
  360.  @Override
  361.     public void run()
  362.     {
  363.                 Log.i("* SurfaceView run"," run start");
  364.                 mRun = true;
  365.                 this.postInvalidate();
  366.                 Log.i("* SurfaceView run"," run stop");
  367.     }
  368.  
  369.  
  370.     public void SetDrawingInBackgroundSleeptime(long _sleepTime) { //long mSleeptime = 20;
  371.     scanvas = surfaceHolder.lockCanvas();
  372.     scanvas.drawBitmap(buffer, 0, 0, paint);
  373.         surfaceHolder.unlockCanvasAndPost(scanvas);
  374.     Log.i("* SurfaceView SetDrawingInBackgroundSleeptime","SetDrawingInBackgroundSleeptime " + _sleepTime);
  375.  
  376.     }
  377.  
  378.  
  379.  
  380.  
  381.     public Bitmap GetDrawingCache() {
  382.         this.setDrawingCacheEnabled(true);
  383.         Bitmap b = Bitmap.createBitmap(this.getDrawingCache());
  384.         this.setDrawingCacheEnabled(false);
  385.         return b;
  386.     }
  387.  
  388. } //end class
  389.  

Code: Pascal  [Select][+][-]
  1. ....AppSurfaceViewDemo1\jni\unit1.pas
I changed the sample demo file as follows.

Code: Pascal  [Select][+][-]
  1. {Hint: save all files to location: C:\adt32\eclipse\workspace\AppSurfaceViewDemo1\jni }
  2. unit unit1;
  3.  
  4. {$mode delphi}
  5.  
  6. interface
  7.  
  8. uses
  9.   Classes, SysUtils, And_jni, And_jni_Bridge, Laz_And_Controls,
  10.     Laz_And_Controls_Events, AndroidWidget, surfaceview, imagefilemanager;
  11.  
  12. type
  13.  
  14.   { TAndroidModule1 }
  15.  
  16.   TAndroidModule1 = class(jForm)
  17.     jButton1: jButton;
  18.     jButton2: jButton;
  19.     jImageFileManager1: jImageFileManager;
  20.     jSurfaceView1: jSurfaceView;
  21.     jTextView1: jTextView;
  22.     procedure AndroidModule1Close(Sender: TObject);
  23.     procedure AndroidModule1JNIPrompt(Sender: TObject);
  24.     procedure jButton1Click(Sender: TObject);
  25.     procedure jButton2Click(Sender: TObject);
  26.     procedure jSurfaceView1DrawOutBackground(Sender: TObject; progress: single);
  27.     procedure jSurfaceView1SurfaceCreated(Sender: TObject);
  28.     procedure jSurfaceView1SurfaceDraw(Sender: TObject; canvas: jObject);
  29.     procedure jSurfaceView1TouchDown(Sender: TObject; Touch: TMouch);
  30.     procedure jSurfaceView1TouchUp(Sender: TObject; Touch: TMouch);
  31.  
  32.   private
  33.     {private declarations}
  34.     FX1, FY1: single;
  35.     FX2, FY2: single;
  36.     FInBackground: boolean;
  37.  
  38.   public
  39.     {public declarations}
  40.   end;
  41.  
  42.   function GetLemurJourney(x: single): single;
  43.  
  44. var
  45.   AndroidModule1: TAndroidModule1;
  46.   GlobalImage: jObject;
  47.   cc:integer=0;
  48.  
  49. implementation
  50.  
  51. {$R *.lfm}
  52.  
  53. { TAndroidModule1 }
  54.  
  55.  
  56.  
  57.  
  58. function GetLemurJourney(x: single): single;
  59. begin
  60.    Result:= x;
  61. end;
  62.  
  63. procedure TAndroidModule1.AndroidModule1JNIPrompt(Sender: TObject);
  64. begin
  65.   GlobalImage:= jImageFileManager1.LoadFromAssets('lemur.jpg');
  66.   GlobalImage:= Get_jObjGlobalRef(GlobalImage);
  67. end;
  68.  
  69. procedure TAndroidModule1.jSurfaceView1SurfaceCreated(Sender: TObject);
  70. var
  71.    canv: jObject;
  72. begin
  73.    FInBackground:= False;
  74.    ShowMessage('Surface Created ...');
  75.    canv:= jSurfaceView1.GetLockedCanvas();
  76.    jSurfaceView1.DrawBackground(canv, colbrLightCyan);
  77.    jSurfaceView1.SetPaintTextSize(36);
  78.    jSurfaceView1.DrawText(canv, 'Hello World!',300,300);
  79.    jSurfaceView1.UnLockCanvas(canv);
  80. end;
  81.  
  82.  
  83. //simple/trivial draw
  84. procedure TAndroidModule1.jButton1Click(Sender: TObject);
  85. begin
  86.   FX1:= 100;
  87.   FY1:= 100;
  88.   FX2:= 250;
  89.   FY2:= 500;
  90.   jSurfaceView1.DispatchOnDraw(True); //true = Allows SurfaceView use Refresh()/Invalidate() to call onDraw() event!
  91.   jSurfaceView1.Invalidate();         //must be called from a main UI thread
  92. end;
  93.  
  94. procedure TAndroidModule1.jButton2Click(Sender: TObject);
  95. begin
  96.   FX1:= 0;
  97.   FY1:= 0;
  98.   FInBackground:= True;
  99.   jSurfaceView1.DispatchOnDraw(true);
  100.   jSurfaceView1.DoDrawingInBackground(True);  //fires  OnDrawingInBackgroundRunning  !!
  101. end;
  102.  
  103.  
  104. //simple/trivial Ondraw event handle
  105. procedure TAndroidModule1.jSurfaceView1SurfaceDraw(Sender: TObject; canvas: jObject);
  106. var
  107.    i:integer;
  108. begin
  109.    jSurfaceView1.DispatchOnDraw(false);
  110.    jSurfaceView1.DrawBackground(canvas,colbrLightBlue);
  111.    inc(cc);
  112.    for i:=0 to Random(750)+100 do
  113.    begin
  114.      jSurfaceView1.DrawBitmap(canvas, GlobalImage, Random(jSurfaceView1.Width), Random(jSurfaceView1.Height));
  115.      jSurfaceView1.DrawLine(canvas, FX1, FY1 , i, i);
  116.      jSurfaceView1.DrawText(canvas,cc.ToString,300,50);
  117.      jSurfaceView1.SetDrawingInBackgroundSleeptime(i); //default/min = 20 miliseconds
  118.    end;
  119.     jSurfaceView1.SetDrawingInBackgroundSleeptime(-1); //default/min = 20 miliseconds
  120. end;
  121.  
  122.  
  123.  
  124. procedure TAndroidModule1.jSurfaceView1DrawOutBackground(Sender: TObject;
  125.   progress: single);
  126. begin
  127.   ShowMessage('The Game is Over...!');
  128.   FInBackground:= False;
  129. end;
  130.  
  131. procedure TAndroidModule1.jSurfaceView1TouchDown(Sender: TObject; Touch: TMouch);
  132. begin
  133.   if not FInBackground then ShowMessage('Touch: X='+ FloatToStr(Touch.Pt.X) + ' Y='+FloatToStr(Touch.Pt.Y) );
  134. end;
  135.  
  136. procedure TAndroidModule1.jSurfaceView1TouchUp(Sender: TObject; Touch: TMouch);
  137. begin
  138.   //
  139. end;
  140.  
  141. procedure TAndroidModule1.AndroidModule1Close(Sender: TObject);
  142. begin
  143.   Delete_jGlobalRef(GlobalImage);
  144. end;
  145.  
  146. end.

 Also, according to my observations, the crash problem in the original example was also fixed. Respects








Check out  loaded on Strava
https://www.strava.com/athletes/109391137

Mongkey

  • Sr. Member
  • ****
  • Posts: 430
Re: Slow down drawing
« Reply #13 on: May 16, 2022, 02:05:21 am »
 :o, thank you @loaded

jmpessoa

  • Hero Member
  • *****
  • Posts: 2297
Re: Slow down drawing
« Reply #14 on: May 16, 2022, 05:26:44 am »

@ loaded
Quote
I converted the SetDrawingInBackgroundSleeptime method directly to the screen refresh method. Don't let the name mislead you.

Can you suggest a "good" method name?    (Don't let the name mislead us...)


Thank you!
Lamw: Lazarus Android Module Wizard
https://github.com/jmpessoa/lazandroidmodulewizard

 

TinyPortal © 2005-2018