Symbian绘制渐变矩形的两种方法

 第一种方法(推荐):

这是我参考其它语言修改成Symbian版本的,使用方法很简单,直接调用DrawShadeRect方法就可以绘制渐变的矩形了。

这种方法原理其实也很简单,感兴趣的可以看看 TransitionalColor这个方法。

static void GetRGBFromHex(TUint aColor,TInt &aRed,TInt &aGreen,TInt &aBlue)  
{  
    aRed    = (aColor & 0xff0000) >> 16;
    aGreen  = (aColor & 0x00ff00) >> 8;  
    aBlue   = (aColor & 0x0000ff);  
}

static void GetHexFromRGB(TUint &aColor,TInt aRed,TInt aGreen,TInt aBlue)  
{  
    
if(aRed < 0 || aRed > 255 || aGreen < 0 || aGreen > 255 || aBlue < 0 || aBlue > 255)
    {
        aColor = 0xFFFFFF;
    }

    aColor =  aRed << 16 | aGreen << 8 | aBlue;  
}  

/*
 * color1是浅色,color2是深色,实现渐变 
 * steps是指在多大的区域中渐变, 
 
*/  
static RArray<TUint> TransitionalColor(TUint aColor1,TUint aColor2,TInt steps)  
{
    RArray<TUint> array;

    
if(steps < 3)  
        
return array;

    TInt R1,G1,B1,R2,G2,B2;
    GetRGBFromHex(aColor1,R1,G1,B1);
    GetRGBFromHex(aColor2,R2,G2,B2);

    array.AppendL(aColor1);
    steps = steps - 2;  

    TInt redDiff    = R2 - R1;  
    TInt greenDiff  = G2 - G1;  
    TInt blueDiff   = B2 - B1;  
    
for(TInt i = 1; i < steps + 1; i++)  
    {
        TUint c;
        GetHexFromRGB(c,
                R1 + redDiff * i / steps,  
                G1 + greenDiff * i / steps,  
                B1 + blueDiff * i / steps  
                );
        array.AppendL(c);
    }  

    array.AppendL(aColor2);
    
return array;  
}  

/*
 * 绘制渐变矩形
 * */
static void DrawShadeRect(CWindowGc& aGc,TRect aRect,TUint aBeginColor,TUint aEndColor)
{
    aGc.SetPenStyle(CGraphicsContext::ESolidPen);

    TInt height = aRect.Height();
    RArray<TUint> colors = TransitionalColor(aBeginColor,aEndColor,height);

    TInt count = colors.Count();
    
for (TInt i = 0;i < height;i++)
    {
        TRgb penColor(colors[i]);
        aGc.SetPenColor(penColor);
        aGc.DrawLine(TPoint(0,i),TPoint(aRect.Width(),i));
    }
    colors.Close();
}

另外绘制渐变渐变矩形还有下面这种方法,但是这种方法效率比较低下,而且效果也不是很理想,建议使用上面直接画线的方法。

第二种方法: 

CFbsBitmap* brush=new(ELeave)CFbsBitmap;
TRgb startColor=KRgbBlue;
TRgb endColor=KRgbWhite; 
TInt brushWidth=10;
ColorUtils::TBitmapOrientation brushOrientation=ColorUtils::EBitmapOrientationVertical;
ColorUtils::CreateGradientBitmapL(*brush, CEikonEnv::Static()->WsSession(), brushWidth, brushOrientation, startColor, endColor);
// bitmap->SetDisplayMode(EColor64K); 如果真机上无法显示,应加上这句代码
gc.DrawBitmap(TRect(aRect.iTl.iX, aRect.iTl.iY, aRect.iBr.iX, aRect.iBr.iY), bitmap);
delete brush;
brush = NULL; 
posted @ 2010-07-27 14:13  1901  阅读(648)  评论(0编辑  收藏  举报