1

此方法将像素颜色从一个图像设置为另一个。如何将 imgPix 数组中的像素设置为 screen.pixels 数组,以使图像在 screen.pixels 数组上显得更大?我简化了代码以使概念易于理解。


public void drawSprite(Screen screen)
{
     for(int y = 0; y < 16; y++)
     {
       for(int x = 0; x < 16; x++)
       {        
           screen.pixels[x + y * screen.WIDTH] = this.imgPix[x + y * this.WIDTH];
       }
     }     
}       
4

2 回答 2

1

我发现一个不错的小技巧是强制转换为 int。这会向下舍入重复模式的数字..

// scale = 2  
-------------y = 0,1,2,3,4,5,6,7,8,9  // as y increase.. y++
(int) y/scale = 0,0,1,1,2,2,3,3,4,4 
//  
// out of  10 numbers 5 were drawn this is scaling up   
// As you can see from the above as y increase y/scale repeats with a the correct pattern  
// this happends because casting the (int) rounds down.   
//  
// scale = 0.8  
-------------y = 0,1,2,3,4,5,6,7,8,9  
(int) y/scale = 0,1,2,3,5,6,7,8,10,11  
//  
// out of  10 numbers 2 were skipped this is scaling down an image


    public void drawSprite(Screen screen,Image image,float scale)
    {
         for(int y = 0; y < image.height*scale; y++)
         {
               int scaleY = (int)(y/scale); 

           for(int x = 0; x < image.width*scale; x++)                          
           {                                                    
               int scaleX = (int)(x/scale); 

               screen.pixels[x + y * screen.WIDTH] = image.pixels[scaleX + scaleY * image.width];
           }
         }     
    }  
于 2013-03-14T02:48:24.987 回答
0

我之前在programmers.stackexchange.com 上回答过这个问题(与java 足够相似):

https://softwareengineering.stackexchange.com/questions/148123/what-is-the-algorithm-to-copy-a-region-of-one-bitmap-into-a-region-in-another/148153#148153

--

struct {
    bitmap bmp;
    float x, y, width, height;
} xfer_param;

scaled_xfer(xfer_param src, xfer_param det)
{
    float src_dx = dst.width / src.width;
    float src_dy = dst.height / src.height;
    float src_maxx = src.x + src.width;
    float src_maxy = src.y + src.height;
    float dst_maxx = dst.x + dst.width;
    float dst_maxy = dst.y + dst.height;
    float src_cury = src.y;

    for (float y = dst.y; y < dst_maxy; y++)
    {
        float src_curx = src.x;   
        for (float x = dst.x; x < dst_maxx; x++)
        {
            // Point sampling - you can also impl as bilinear or other
            dst.bmp[x,y] = src.bmp[src_curx, src_cury];
            src_curx += src_dx;
        }

        src_cury += src_dy;
    }
}
于 2012-10-26T06:45:48.493 回答