能将图形水平翻转的函数
能将图形水平翻转的函数
做2D游戏时应该用得到,将图形水平翻转,尤其是人物素材,可将本来朝向右边的翻转成朝向左边的。
[cpp]- #include <string.h>
- int flip_horizontal(
- int img_width,
- int img_hight,
- unsigned char *in_red,//传入的红色
- unsigned char *in_green,//传入的绿色
- unsigned char *in_blue,//传入的蓝色
- unsigned char *in_alpha//传入的透明度
- )
- //水平翻转图像
- {
- int x,y,pos,temp;
- unsigned char *out_red;//传出的红色
- unsigned char *out_green;//传出的绿色
- unsigned char *out_blue;//传出的蓝色
- unsigned char *out_alpha;//传出的透明度
- out_red = (unsigned char*)malloc(img_width*img_hight);//申请内存
- out_green = (unsigned char*)malloc(img_width*img_hight);
- out_blue = (unsigned char*)malloc(img_width*img_hight);
- out_alpha = (unsigned char*)malloc(img_width*img_hight);
- temp = 0;
- for (y=0;y<img_hight;y++) {//y的初始值为0,小于图片的高度,y自增
- //y表示的是图片第几行
- pos = y*img_width + img_width-1;
- for (x=0;x<img_width;x++) {
- out_red[pos] = in_red[temp];
- out_green[pos] = in_green[temp];
- out_blue[pos] = in_blue[temp];
- out_alpha[pos] = in_alpha[temp];
- ++temp;
- --pos;
- //假设img_width = 10,当y=0时,那么,out_red[9] = in_red[0],以此类推
- //当y=1时,out_red[19] = in_red[10],以此类推
- //把图片的每一行水平翻转
- }
- }
- memcpy(in_red,out_red,img_width*img_hight);//拷贝
- memcpy(in_green,out_green,img_width*img_hight);
- memcpy(in_blue,out_blue,img_width*img_hight);
- memcpy(in_alpha,out_alpha,img_width*img_hight);
- free(out_red);
- free(out_blue);//释放内存
- free(out_green);
- free(out_alpha);
- return 0;
- }
上面的是最初写的代码,现在想了一下,没必要申请内存存储翻转后的图形数组,于是,改成了这个:
[cpp]
- #include "game_data.h"
- int flip_horizontal(Action_Graph *src)
- /* 将图像进行水平翻转 */
- {
- int value = 0,x,y,pos,temp,count;
- int width = src->width,hight = src->height;
- unsigned char buff;
- if(src->malloc != IS_TRUE) {
- value = -1;
- }
- else{
- temp = (int)width/2;
- for (y=0;y<hight;y++) {
- /* 水平翻转其实也就是交换两边的数据 */
- pos = y*img_width;
- for (x=0;x<temp;x++) {
- count = img_width - x - 1;
- buff = src->rgba[0][pos+x];
- src->rgba[0][pos+x] = src->rgba[0][count];
- src->rgba[0][count] = buff;
- buff = src->rgba[1][pos+x];
- src->rgba[1][pos+x] = src->rgba[1][count];
- src->rgba[1][count] = buff;
- buff = src->rgba[2][pos+x];
- src->rgba[2][pos+x] = src->rgba[2][count];
- src->rgba[2][count] = buff;
- buff = src->rgba[3][pos+x];
- src->rgba[3][pos+x] = src->rgba[3][count];
- src->rgba[3][count] = buff;
- /* “命中”点阵图的翻转 */
- if(src->hit_flag == IS_TRUE){
- buff = src->hit[pos+x];
- src->hit[pos+x] = src->hit[count];
- src->hit[count] = buff;
- }
- /* “攻击”点阵图的翻转 */
- if(src->atk_flag == IS_TRUE){
- buff = src->atk[pos+x];
- src->atk[pos+x] = src->atk[count];
- src->atk[count] = buff;
- }
- }
- }
- }
- return value;
- }
评论暂时关闭