J2ME 渐变色的处理方法

来源:互联网 发布:淘宝旗舰店是什么意思 编辑:程序博客网 时间:2024/05/29 17:31

基于MIDP2.0 CLDC1.0。是我自己一直在用的一个方法,基本机型都是支持的。只要在paint调用即可

Java代码
  1. private static int[] retrieveRGBComponent(int color) {  
  2.     int[] rgb = new int[3];  
  3.     rgb[0] = (color & 0x00ff0000) >> 16;  
  4.     rgb[1] = (color & 0x0000ff00) >> 8;  
  5.     rgb[2] = (color & 0x000000ff);  
  6.     return rgb;  
  7. }  
  8.   
  9. private static int[] generateTransitionalColor(int color1, int color2,  
  10.         int steps) {  
  11.     int[] color1RGB = retrieveRGBComponent(color1);  
  12.     int[] color2RGB = retrieveRGBComponent(color2);  
  13.     if (steps < 3 || color1RGB == null || color2RGB == null)  
  14.         return null;  
  15.     int[] colors = new int[steps];  
  16.     colors[0] = color1;  
  17.     colors[colors.length - 1] = color2;  
  18.     steps = steps - 2;  
  19.     int redDiff = color2RGB[0] - color1RGB[0];  
  20.     int greenDiff = color2RGB[1] - color1RGB[1];  
  21.     int blueDiff = color2RGB[2] - color1RGB[2];  
  22.     // from the second to the last second.  
  23.     for (int i = 1; i < colors.length - 1; i++) {  
  24.         colors[i] = generateFromRGBComponent(new int[] {  
  25.                 color1RGB[0] + redDiff * i / steps,  
  26.                 color1RGB[1] + greenDiff * i / steps,  
  27.                 color1RGB[2] + blueDiff * i / steps });  
  28.     }  
  29.     return colors;  
  30. }  
  31.   
  32. private static int generateFromRGBComponent(int[] rgb) {  
  33.     if (rgb == null || rgb.length != 3 || rgb[0] < 0 || rgb[0] > 255  
  34.             || rgb[1] < 0 || rgb[1] > 255 || rgb[2] < 0 || rgb[2] > 255)  
  35.         return 0xfffff;  
  36.     return rgb[0] << 16 | rgb[1] << 8 | rgb[2];  
  37. }  
  38.   
  39. /** 
  40.  *  
  41.  * @param g 
  42.  * @param x 
  43.  *            起始X 
  44.  * @param y 
  45.  *            起始Y 
  46.  * @param width 
  47.  *            宽度 
  48.  * @param height 
  49.  *            高度 
  50.  * @param TransStart 
  51.  *            渐变开始颜色 
  52.  * @param TransEnd 
  53.  *            渐变结束颜色 
  54.  */  
  55. public void drawSelectedBackground(Graphics g, int x, int y, int width,  
  56.         int height, int TransStart, int TransEnd) {  
  57.     // 这样写是从左到右渐变  
  58.     // int[] line = generateTransitionalColor(TextShade, TransEnd, width);  
  59.     // Image lineImg = Image.createRGBImage(line, line.length, 1, false);  
  60.     // for (int i = 0; i < height; i++) {  
  61.     // g.drawImage(lineImg, x, y + i, Graphics.LEFT | Graphics.TOP);  
  62.     // }  
  63.   
  64.     // 下面的写法是从上到下渐变  
  65.     int[] line = generateTransitionalColor(TransStart, TransEnd, height);  
  66.     Image lineImg = Image.createRGBImage(line, 1, line.length, false);  
  67.     for (int i = 0; i < width; i++) {  
  68.         g.drawImage(lineImg, x + i, y, Graphics.LEFT | Graphics.TOP);  
  69.     }  
  70. }  
原创粉丝点击