J2ME 实现半透明效果

时间:2022-04-26 20:07:19

 如果是图片:

 /** */
 /**
  * 创建半透明图片(MIDP2.0)
  * @param path 源PNG图片路径
  * @return 创建好的半透明图片
  */
 Image createAlphaImage(Image tmpImage) {
  try {
   int[] data = new int[tmpImage.getWidth() * tmpImage.getHeight()];
   tmpImage.getRGB(data, 0, tmpImage.getWidth(), 0, 0, tmpImage
     .getWidth(), tmpImage.getHeight());
   int len = data.length;
   for (int i = 0; i < len; i++) {
    //0x65000000为半透明度,可根据需要适当调整
    /* 此处是可以更改部分像素颜色
     if(data[i] == 0xFFCC8866)
     {
     data[i] = 0xFFCC8800;
     continue;
     }*/
    data[i] = data[i] + 0x50000000;
   }
   return Image.createRGBImage(data, tmpImage.getWidth(), tmpImage
     .getHeight(), true);
  } catch (Exception e) {
   System.out.println("create Alpha Image fail!!");
   return null;
  }
 }

 

也可以直接用代码画半透明效果:

static int[] s_transparentBuf;
final static int   TRANSPARENT_BUF_H = 1;
private static void fillTransparentRect( Graphics gra, int x, int y, int width, int height, int r, int g, int b, int transPercent )
{
      transPercent = 255 * transPercent / 100;

      if(s_transparentBuf == null || s_transparentBuf.length / TRANSPARENT_BUF_H < width){
          s_transparentBuf = null;
          s_transparentBuf = new int[width * TRANSPARENT_BUF_H];
      }

      int len = s_transparentBuf.length;
      for( int i = 0; i < len; i++ ){
          s_transparentBuf[i] = (transPercent << 24) + (r << 16) + (g << 8) + b;
      }
 
      for ( int i=0; i<height; i+=1 )
      {
          gra.drawRGB(s_transparentBuf, 0, width, x, y+i, width, 1, true);
      }
}