Domanda

Still working my way through leaning WinAPI and its various libraries, and I'm now trying to figure out GDI+. As a simple test, I'm trying to load an image from a file and draw it to the screen.

Here's the code I'm using (explanation below it):

int x=0, y=0;
Image* sprite=Image::FromFile((WCHAR*)"MyImage.png");
Graphics g(dc);
std::cout<<"(x, y)=("<<x<<", "<<y<<")"<<std::endl; // Debug output
std::cout<<"(w, h)=("<<sprite->GetWidth()<<", "<<sprite->GetHeight()<<")"<<std::endl; // Debug output
g.DrawImage(sprite, x, y, (int)sprite->GetWidth(), (int)sprite->GetHeight());

So dc is the HDC I'm drawing to, obtained via BeginPaint(). It's definitely fine, because I can draw an ellipse with Ellipse() using that HDC and it shows up fine. I've output the sprite variable's value, and it's a non-null pointer, as it should be.

The weird part is that the output above says the width and height of the image are both 0. What would cause that? I thought maybe the image wasn't being loaded properly, so I tried using both an absolute and a relative path for the FromFile() argument, and nothing changed. I also tried switching from a PNG to a BMP, but no change there, either.

What's going on?

EDIT Just tested, and if I load the image as Image* sprite=new Image(L"Path_To_Image"); it works fine. Why doesn't it work with FromFile?

È stato utile?

Soluzione

Gdiplus expects Unicode strings for methods like Image::FromFile.

However in your code you are passing a multibyte string. Simply casting to WCHAR* isn't enough to convert a string to Unicode - you need to prefix it with L (and you should then remove the cast, which isn't necessary).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top