Hello Mobile: Your First Mobile SDL 2 App

本文介绍如何在移动设备上使用SDL库创建并运行应用程序,包括获取设备显示模式、创建窗口,并展示了主循环中事件处理、渲染和更新屏幕的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Now that you covered the hard part of getting the application to compile and run, let's go over the application code.

//Screen dimensions SDL_Rect gScreenRect = { 0, 0, 320, 240 };

Since mobile devices vary a lot in resolution, we're going to use variable screen dimensions instead of constant ones.

//Get device display mode SDL_DisplayMode displayMode; if( SDL_GetCurrentDisplayMode( 0, &displayMode ) == 0 ) { gScreenRect.w = displayMode.w; gScreenRect.h = displayMode.h; } //Create window gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, gScreenRect.w, gScreenRect.h, SDL_WINDOW_SHOWN ); if( gWindow == NULL ) { SDL_Log( "Window could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; }

Here we call SDL_GetCurrentDisplayMode to get the resolution of the mobile device. We then create a window using the device dimensions.

Notice how we're using SDL_Log instead of printf. This is because Android/iOS have their own platform specific ways to print to the console and SDL gives us a nice wrapper to make our code cross platform.

int main( int argc, char* args[] ) { //Start up SDL and create window if( !init() ) { SDL_Log( "Failed to initialize!\n" ); } else { //Load media if( !loadMedia() ) { SDL_Log( "Failed to load media!\n" ); } else { //Main loop flag bool quit = false; //Event handler SDL_Event e; //While application is running while( !quit ) { //Handle events on queue while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; } } //Clear screen SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); SDL_RenderClear( gRenderer ); //Render splash gSplashTexture.render( ( gScreenRect.w - gSplashTexture.getWidth() ) / 2, ( gScreenRect.h - gSplashTexture.getHeight() ) / 2 ); //Update screen SDL_RenderPresent( gRenderer ); } } } //Free resources and close SDL close(); return 0; }

Other than the fact that we're using SDL_Log, the code is pretty much the same as before.

Download the media and source code for this tutorial here.

http://lazyfoo.net/tutorials/SDL/52_hello_mobile/index2.php

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值