Android SurfaceView example

Source: Internet
Author: User
Tags drawtext

SurfaceView is generally used for games.

[Java]
Package com. himi;
Import android. content. Context;
Import android. graphics. Canvas;
Import android. graphics. Color;
Import android. graphics. Paint;
Import android. view. SurfaceHolder;
Import android. view. SurfaceView;
Import android. view. SurfaceHolder. Callback;
Import android. view. animation. Animation;
/**
* @ Author Himi
*/
Public class MySurfaceView extends SurfaceView implements Callback, Runnable {// Note 1
Private SurfaceHolder sfh;
Private Thread th;
Private Canvas canvas;
Private Paint paint;
Private int ScreenW, ScreenH;
Public MySurfaceView (Context context ){
Super (context );
Th = new Thread (this );
Sfh = this. getHolder ();
Sfh. addCallback (this); // Note 1
Paint = new Paint ();
Paint. setAntiAlias (true );
Paint. setColor (Color. RED );
This. setKeepScreenOn (true); // keep the screen always on
}
@ Override
Public void startAnimation (Animation animation ){
Super. startAnimation (animation );
}
Public void surfaceCreated (SurfaceHolder holder ){
ScreenW = this. getWidth (); // Note 2
ScreenH = this. getHeight ();
Th. start ();
}
Private void draw (){
Try {
Canvas = sfh. lockCanvas (); // get a canvas instance.
Canvas. drawColor (Color. WHITE); // screen Flushing
Canvas. drawText ("Himi", 100,100, paint); // draw text
Canvas. drawText ("this is a simple game framework", 100,130, paint );
Sfh. unlockCanvasAndPost (canvas); // submit the painted canvas
} Catch (Exception ex ){
} Finally {// Note 3
If (canvas! = Null)
Sfh. unlockCanvasAndPost (canvas );
}
}
Public void run (){
While (true ){
Draw ();
Try {
Thread. sleep (100 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}
Public void surfaceChanged (SurfaceHolder holder, int format, int width,
Int height ){
}
Public void surfaceDestroyed (SurfaceHolder holder ){
// TODO Auto-generated method stub
}
}

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.