[笔记]音视频学习之SDL篇《七》用类封装SDL

简介: [笔记]音视频学习之SDL篇《七》用类封装SDL

前言

更好使用SDL库 封装成类可以更好使用

封装过程 如别人教程 我稍作修改了 直接贴源码好了

主要封装

1.载入图片

2.载入字体

3.事件循环

…

实现

Window.h

#ifndef WINDOW_H
#define WINDOW_H
#include <string>
#include <stdexcept>
#include <memory>
#include <SDL2/SDL.h>
#include <functional>
#include <vector>
//What we think our window class should look like
class Window {
public:
    //Start SDL and TTF, create the window and renderer
    static void Init(std::string title);
    //Quit SDL and TTF
    static void Quit();
    //Draw an SDL_Texture
    static void Draw(SDL_Texture* tex, SDL_Rect& dstRect, SDL_Rect* clip,
        float angle, int xPivot, int yPivot,SDL_RendererFlip flip);
    //Load an image
    static SDL_Texture* LoadImage(std::string file);
    //Render some text
    static SDL_Texture* RenderText(std::string strText, std::string file, SDL_Color color, int fontSize);
    static void HandleEvents(const std::function<void(SDL_Event&)>& cbFunction);
    //Clear window
    static void Clear();
    //Present renderer
    static void Present();
    //Get the window's box
    static SDL_Rect Box();
public:
    static std::unique_ptr<SDL_Window, void (*)(SDL_Window*)> m_pWindow;
    static std::unique_ptr<SDL_Renderer, void (*)(SDL_Renderer*)> m_pRenderer;
    static SDL_Rect m_pBox;
    static bool m_eventQuit;
};
#endif

Window.cpp

#include <string>
#include <stdexcept>
#include <memory>
#include <fstream>
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include<algorithm>
#include "window.h"
//Initialize the unique_ptr's deleters here
std::unique_ptr<SDL_Window, void (*)(SDL_Window*)> Window::m_pWindow = std::unique_ptr<SDL_Window, void (*)(SDL_Window*)>(nullptr, SDL_DestroyWindow);
std::unique_ptr<SDL_Renderer, void (*)(SDL_Renderer*)> Window::m_pRenderer = std::unique_ptr<SDL_Renderer, void (*)(SDL_Renderer*)>(nullptr, SDL_DestroyRenderer);
bool Window::m_eventQuit = false;
//Other static members
SDL_Rect Window::m_pBox;
void Window::Init(std::string title = "Window") {
    //initialize all SDL subsystems
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
        throw std::runtime_error("SDL Init Failed");
    if (TTF_Init() == -1)
        throw std::runtime_error("TTF Init Failed");
    //Setup our window size
    m_pBox.x = 0;
    m_pBox.y = 0;
    m_pBox.w = 640;
    m_pBox.h = 480;
    //Create our window
    m_pWindow.reset(SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED, m_pBox.w, m_pBox.h, SDL_WINDOW_SHOWN));
    //Make sure it created ok
    if (m_pWindow == nullptr)
        throw std::runtime_error("Failed to create window");
    //Create the renderer
    m_pRenderer.reset(SDL_CreateRenderer(m_pWindow.get(), -1,
        SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC));
    //Make sure it created ok
    if (m_pRenderer == nullptr)
        throw std::runtime_error("Failed to create renderer");
}
void Window::Quit() {
    TTF_Quit();
    SDL_Quit();
}
void Window::Draw(SDL_Texture* tex, SDL_Rect& dstRect, SDL_Rect* clip = NULL,
    float angle = 0.0, int xPivot = 0, int yPivot = 0,SDL_RendererFlip flip = SDL_FLIP_NONE) {
}
SDL_Texture* Window::LoadImage(std::string file) {
    SDL_Surface* bmp = IMG_Load(file.c_str());
    if (bmp == nullptr)
    {
        throw std::runtime_error("SDL_LoadBMP Error");
        std::cout << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl;
        return nullptr;
    }
    //SDL_Texture来用硬件加速绘制图像
    SDL_Texture* tex = SDL_CreateTextureFromSurface(m_pRenderer.get(), bmp);
     SDL_FreeSurface(bmp);
    if (tex == nullptr)
    {
        std::cout << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl;
        throw std::runtime_error("SDL_CreateTextureFromSurface Error");
        return nullptr;
    }
    SDL_RenderClear(m_pRenderer.get());
    //texture画上去
    //第一个NULL是一个指向源矩形的指针,也就是说,从图像上裁剪下的一块矩形
    //而另一个是指向目标矩形的指针。我们将NULL传入这两个参数,
    //是告诉SDL绘制整个源图像(第一个NULL),并把它画在屏幕上(0,0 )的位置,并拉伸这个图像让它填满整个窗口(第二个NULL)
    SDL_RenderCopy(m_pRenderer.get(), tex, NULL, NULL);// 
    SDL_RenderPresent(m_pRenderer.get());// SDL_RenderPresent来更新屏幕的画面
  return tex;
}
SDL_Texture* Window::RenderText(std::string message, std::string fontFile, SDL_Color color, int fontSize){
        //Open the font
        TTF_Font* font = TTF_OpenFont(fontFile.c_str(), fontSize);
        if (font == nullptr) {
            printf("TTF_OpenFont error");
            return nullptr;
        }
        //We need to first render to a surface as that's what TTF_RenderText returns, then
        //load that surface into a texture
        SDL_Surface* surf = TTF_RenderText_Blended(font, message.c_str(), color);
        if (surf == nullptr) {
            TTF_CloseFont(font);
            printf("TTF_RenderText error");
            return nullptr;
        }
        SDL_Texture* texture = SDL_CreateTextureFromSurface(m_pRenderer.get(), surf);
        if (texture == nullptr) {
            printf("CreateTexture");
            return nullptr;
        }
        //Clean up the surface and font
        SDL_FreeSurface(surf);
        TTF_CloseFont(font); 
        SDL_Rect* clip = nullptr;
        SDL_Rect pos = { Window::Box().w / 2 - 150 / 2,
         Window::Box().h / 2 - 150 / 2, 150, 150 };
        //The angle to draw at, so we can play with it
        int angle = 0;
        SDL_RenderCopy(m_pRenderer.get(), texture, clip, &pos);
        SDL_RenderPresent(m_pRenderer.get());
        return texture;
}
void Window::HandleEvents(const std::function<void(SDL_Event&)> &cbFunction) {
    m_eventQuit = false;
    SDL_Event e;
    while (!m_eventQuit) {
        while (SDL_PollEvent(&e)) {
            cbFunction(e);
        }
    }
}
void Window::Clear(){
    SDL_RenderClear(m_pRenderer.get());
}
void Window::Present() {
    SDL_RenderPresent(m_pRenderer.get());
}
SDL_Rect Window::Box() {
    //Update mBox to match the current window size
    SDL_GetWindowSize(m_pWindow.get(), &m_pBox.w, &m_pBox.h);
    return m_pBox;
}

main.cpp

#include <string>
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include "Window.h"
#include "res_path.h"
#include "cleanup.h"
int main() {
  //Show A Window
  //In main()
  //Load up an image and some text
  SDL_Texture* img, * msg;
  try {
    //Start our window
    Window::Init("Shiver's GUI");
    Window::HandleEvents([](SDL_Event e) {
      switch (e.key.keysym.sym) {
      case SDLK_q:
      case SDLK_ESCAPE:
        Window::m_eventQuit = true;
        break;
      }
      if (e.key.keysym.sym == SDLK_a) {
        printf("keydown A \n");
        Window::Clear();
        std::string fontFile = "..\\..\\res\\06sdl_learn\\sample.ttf";
        std::string text = "TTF Fonts too!";
        SDL_Color color = { 255, 255, 255 };
        Window::RenderText(text, fontFile, color, 25);
      }
      if (e.key.keysym.sym == SDLK_f) {
        printf("keydown F \n");
        //Load the image
        std::string imgFile = "..\\..\\res\\01sdl_learn\\preview2.bmp";
        Window::LoadImage(imgFile);
      }
    });
  }
  catch (const std::runtime_error& e) {
    //Catch error and crash
    std::cout << e.what() << std::endl;
    Window::Quit();
    return -1;
  }
}

总结

demo地址

后续会继续进行封装作为个人使用库使用

相关文章
|
12月前
|
存储 人工智能 机器人
【2026必看 AI智能体】零基础Coze平台使用教程
本文介绍了Coze智能体的实战入门与进阶应用,涵盖智能体创建、配置大语言模型(LLM)、使用插件扩展功能、构建知识库(RAG)实现高考志愿填报助手、利用记忆功能开发记账本,以及通过API调用和工作流实现中草药识别与菜谱生成等复杂任务,全面展示其在多场景下的智能化能力。
9356 11
|
6月前
|
人工智能 网络安全 新制造
孟庆涛:AI 为什么会 “说谎”?GEO 给出了终极答案
生成式AI时代,“幻觉危机”正威胁品牌真实——Gartner指出品牌信息错误率高达37%。辽宁粤穗孟庆涛首创“生成式引擎优化(GEO)”,以权威信源布局、可溯源数据嵌入、交叉验证结构、虚假信息对冲四大技术,让品牌成为AI信赖的“高优先级食材”,筑牢信任护城河。(239字)
389 0
|
存储 开发框架 移动开发
|
8月前
|
人工智能 安全 自动驾驶
企业AI治理必读:JBoltAI Agent OS核心逻辑
JBoltAI Agent OS是企业级AI智能体治理平台,解决本地化Agent爆发带来的权限失控、审计缺失、技能孤岛与转型黑盒四大难题。它不替代Agent,而是作为“数字交通局”,提供统一授权、全链路审计、技能共享与AI驾驶舱四大能力,让千百个智能体在安全可控中高效协同。(239字)
287 7
|
9月前
|
人工智能 API 数据安全/隐私保护
最新OpenClaw部署指南:阿里云无影云电脑一键上手,本地部署+Skills集成零门槛+常见问题
在AI智能体技术飞速迭代的2026年,OpenClaw(原Clawdbot,业内昵称“龙虾”)凭借“自然语言交互+实际任务执行”的核心能力,成为个人办公提效、中小企业轻量化数字化转型的热门工具。它区别于传统聊天式AI,真正实现了“指令下达即任务落地”,可通过简单的自然语言指令,完成文件管理、浏览器自动化、数据处理、多工具协同等实际操作,而其模块化的Skills(技能)系统,更让AI智能体的功能得以无限延伸,适配不同领域的个性化需求,无论是职场新人还是技术小白,都能借助它解放双手、提升效率。
1106 1
|
11月前
|
设计模式 人工智能 程序员
【架构演进】智能体来了(西南总部)深度解析:多智能体协作(Multi-Agent)系统的设计哲学与工程实践
本文探讨AI架构从单体大模型向多智能体系统(MAS)的范式跃迁,基于“智能体来了(西南总部)”技术研判,解析角色解耦、消息路由与共享记忆等核心设计,揭示如何构建高效协作的“数字蜂群”,推动分布式AI从理论走向工程化落地。
994 2
|
12月前
|
消息中间件 人工智能 供应链
云原生时代的企业增长:如何融合AI获客服务与阿里云构建智能营销引擎
2025年,企业增长依赖云、数据与AI的融合。阿里云提供坚实底座,链创AI等专业SaaS赋能获客。通过API集成,实现数据闭环、智能叠加与成本优化,构建弹性、可观测的云原生营销引擎,驱动业务创新与竞争优势。
|
人工智能 监控 负载均衡
一文详述:AI 网关与 API 网关到底有什么区别?
近年来,AI发展迅猛,大模型成为推动业务创新的关键力量。企业面临如何安全管理和部署AI应用的挑战,需设计既能满足当前需求又可适应未来发展的基础架构。AI网关应运而生,在集成、管理和优化AI应用中扮演重要角色。本文探讨AI网关与API网关的区别,分析AI系统为何需要专门网关,并提供选择合适AI网关的建议。AI网关不仅支持多种模型,还具备高级安全性和性能优化功能,有助于企业在复杂环境中灵活应用AI技术。
1278 2
|
SQL 缓存 监控
Oracle 亿级数据 插入 实战方案
本方案提供高效数据插入实施指南,涵盖环境评估、技术选型、分阶段实施、RAC优化、监控应急及性能验证,确保大规模数据加载稳定高效,已在生产环境验证1.2亿条数据3.5小时内完成插入。
|
文字识别 Python
python做ocr卡证识别很简单
本示例展示了如何使用 `potencent` 库调用腾讯云 OCR 服务识别银行卡和身份证信息。代码中分别通过本地图片路径 (`img_path`) 和配置文件 (`potencent-config.toml`) 实现了银行卡和身份证的 OCR 识别,并输出结果。测试图片及结果显示了识别效果,需提前配置腾讯云的 `SECRET_ID` 和 `SECRET_KEY`。
798 8