type
status
date
slug
summary
tags
category
icon
password
#include <iostream> #include "SDL2/SDL.h" #include "SDL2_image/SDL_image.h" #include "demo_sdl.h" using namespace std; const int WIDTH = 1000; const int HEIGHT = 600; void showImage() { if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { cout << "初始化失败" << endl; return; } SDL_Window *window = SDL_CreateWindow("Show Image", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN); if (window == nullptr) { cout << "创建Window失败:" << SDL_GetError() << endl; return; } SDL_Renderer *renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_ACCELERATED); if (renderer == nullptr) { cout << "创建Renderer失败:" << SDL_GetError() << endl; return; } SDL_Surface *image = IMG_Load("/Volumes/T5/CppPractice/renderer-dog/res/demo.jpg"); if (!image) { cout << "加载图片失败:" << SDL_GetError() << endl; return; } // 如果使用硬件加速,则必须将Surface转换成Texture SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, image); SDL_FreeSurface(image); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, nullptr, nullptr); SDL_RenderPresent(renderer); SDL_Event windowEvent; while (true) { if (SDL_PollEvent(&windowEvent)) { if (windowEvent.type == SDL_QUIT) { std::cout << "终止程序" << std::endl; break; } } } SDL_DestroyRenderer(renderer); SDL_DestroyTexture(texture); SDL_DestroyWindow(window); SDL_Quit(); }

基本步骤

  1. 初始化
  1. 创建Window
  1. 创建Renderer,用于在Window上渲染内容
  1. 创建Surface,Surface其实就是像素的载体
  1. 如果需要使用硬件加速,需要将Surface转换成Texture
  1. 清除Renderer内容,并使用Renderer的Copy功能将texture内容复制到屏幕的指定区域
  1. 指定当前的Renderer.
  1. 事件监听
  1. 销毁各种对象

遇到的问题

  • MacOS安装的SDL2_image库打开时提示安全提示
    • 解决方案:
      sudo spctl --master-disable

源码

skia-基本图形的绘制用SDL写个HelloWorld
姜康
姜康
一个软件工程师
公告
type
status
date
slug
summary
tags
category
icon
password
🎉博客网站重新制作了🎉
👏欢迎更新体验👏