# [SDL] SDL 2D Rotation

wolf1oo w.olf1oo at yahoo.com
Mon Mar 22 19:40:36 PDT 2010

```Well, I had been looking for a couple of days for ways to rotate parts of images etc. with the SDL library, but I only found that people said to use the opengl rotate functions.
I didn't quite like this alternative  :P

So, here is what I came up with.

Code:
void SDL_Rotate(SDL_Surface *surface, SDL_Rect *rect, float angle, int x, int y) {
SDL_LockSurface(surface);
int bpp = surface->format->BytesPerPixel;
int white = SDL_MapRGB(surface->format,0xff,0xff,0xff);
char* pixels = (char*)malloc(surface->w*surface->h*bpp);
for (int i = surface->w*surface->h; i >= 0; --i) {
char* c = pixels+i*bpp;
memcpy(c,&white,bpp);
}
for(int sx = surface->w; sx >= 0; --sx) {
for (int sy = surface->h; sy >= 0; --sy) {
if (sx >= rect->x && sx < (rect->x+rect->w) && sy >= rect->y && sy < (rect->y+rect->h)) { //Point in surface is part of rect
float curangle;
if (sx-x == 0) {curangle = 90;}
else {curangle = atan((float)(sy-y)/(float)(sx-x)) * 180/3.14159;}
float l = sqrt(pow(sx-x,2)+pow(sy-y,2));
char* p = (char*)surface->pixels+sx*bpp+sy*surface->pitch;
char* q = (char*)pixels+((int)(cos((angle+curangle)*3.14159/180)*l)+x)*bpp+((int)(sin((angle+curangle)*3.14159/180)*l)+y)*surface->pitch;
memcpy(q,p,bpp);
if(memcmp(q+bpp,&white,bpp) == 0) {
memcpy(q+bpp,q,bpp); //To effectively cover without many/any holes
}
}
}
}
memcpy(surface->pixels,pixels,surface->w*surface->h*bpp);
SDL_UnlockSurface(surface);
}

As you can see, it only really needs the normal C math library. Other than that, its pretty straightforward and heeds pretty good results, if you want to rotate without getting to nit-picky in detail. The arguments are pretty obvious, and x and y describes the point of rotation. The surface of course must be updated afterward as well.

With my luck it has probably already been done before, as I expect it has, but I was unable to find it. But just in case others needed some reference.....

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.libsdl.org/pipermail/sdl-libsdl.org/attachments/20100322/486ca85f/attachment.htm>
```