SwitchGame/source/EngineFrame/Component/Sprite.cpp

123 lines
2.3 KiB
C++
Raw Normal View History

2025-09-15 11:28:54 +08:00
#include "Sprite.h"
#include "EngineCore/Game.h"
#include "Text.h"
Sprite::Sprite()
{
}
Sprite::Sprite(std::string imgPath, int Index)
{
Init(imgPath, Index);
}
Sprite::~Sprite()
{
SDL_DestroyTexture(m_texture);
}
void Sprite::Init(std::string imgPath, int Index)
{
Asset_ImagePack::IMG *Info = Asset_ImagePack::GetInstance().GetIMG(imgPath);
Asset_ImagePack::ImgInfo &Buf = Info->lp_lplist[Index];
m_texture = SDL_CreateTexture(
Game::GetInstance().GetRenderer(),
SDL_PIXELFORMAT_ARGB8888, // 匹配RGBA数据格式
SDL_TEXTUREACCESS_STREAMING,
Buf.Width, Buf.Height);
if (!m_texture)
{
SDL_Log("纹理创建失败: %s", SDL_GetError());
}
int pitch = Buf.Width * 4;
SDL_UpdateTexture(m_texture, NULL, Buf.PNGdata, pitch);
if (Info != NULL)
{
// SDL_Log("第%d张图片的宽度为%d高度为%d\n", Index, Buf.Width, Buf.Height);
}
TextureSize.x = Buf.Width;
TextureSize.y = Buf.Height;
Size.x = Buf.Width;
Size.y = Buf.Height;
}
SDL_Texture *Sprite::GetTexture()
{
return m_texture;
}
void Sprite::HandleEvents(SDL_Event *e)
{
}
void Sprite::Update(float deltaTime)
{
}
void Sprite::Render(float deltaTime)
{
SDL_Renderer *renderer = Game::GetInstance().GetRenderer();
if (!m_texture)
return;
SDL_Rect dstrect = {Pos.x, Pos.y, Size.x, Size.y};
if (Angle != 0 || flip != SDL_FLIP_NONE)
{
SDL_RenderCopyEx(renderer, m_texture, NULL, &dstrect, Angle, &Anchor, flip);
}
else
SDL_RenderCopy(renderer, m_texture, NULL, &dstrect);
}
void Sprite::Clear()
{
}
void Sprite::SetPos(SDL_Point pos)
{
Pos = pos;
}
void Sprite::SetBlendMode(SDL_BlendMode blendMode)
{
SDL_SetTextureBlendMode(m_texture, blendMode);
}
void Sprite::SetAngle(float angle)
{
Angle = angle;
}
void Sprite::SetAnchor(SDL_FPoint anchor)
{
Anchor.x = Size.x * anchor.x;
Anchor.y = Size.y * anchor.y;
}
SDL_Point Sprite::GetPos()
{
return Pos;
}
SDL_BlendMode Sprite::GetBlendMode()
{
SDL_BlendMode blendMode;
SDL_GetTextureBlendMode(m_texture, &blendMode);
return blendMode;
}
float Sprite::GetAngle()
{
return Angle;
}
SDL_FPoint Sprite::GetAnchor()
{
SDL_FPoint P;
P.x = Anchor.x / Size.x;
P.y = Anchor.y / Size.y;
return P;
}