在GUI控件上放置图片,并在图片上输出半透明文字(转)

主要使用到的是java.awt.image.*包,继承RGBImageFilter类,对图片的像素进行alpha(透明度)进行修改,下面以applet为例:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.image.*;

public class applet6 extends Applet {
MediaTracker mt;
Image img=null;
Image im=null;
ImageFilter imgf=null;
FilteredImageSource fis=null;
public void init() {
img=this.getImage(this.getCodeBase(),"d.jpg");
mt=new MediaTracker(this);
mt.addImage(img,0);
try {
mt.waitForAll(0);
} catch(Exception ex) {System.err.println(ex.toString());}
im=this.createImage(100,100);//建立新的图片,用于输入文字,以便接下来进行透明处理
Graphics g2=im.getGraphics();
g2.setFont(new Font("宋体",Font.BOLD,15));
g2.drawString("半透明文字",10,50);
imgf=new myImage(100,100,100);//调用自定义类进行对象构造
fis=new FilteredImageSource(im.getSource(),imgf);//对图象的源(图象生产者)进行过滤处理,构造出FilteredImageSource对象实例
im=this.createImage(fis);//通过FilteredImageSource实例生成Image
}

public void paint(Graphics g) {
g.drawImage(img,0,0,this);//画出图片
g.drawImage(im,100,100,this);//添加半透明文字
}
}

class myImage extends RGBImageFilter {//抽象类RGBImageFilter是ImageFilter的子类,继承它实现图象ARGB的处理
int width=0;
int height=0;
int alpha=0;
public myImage(int width,int height,int alpha) {//构造器,用来接收需要过滤图象的尺寸,以及透明度
this.canFilterIndexColorModel=true;
//TransparentImageFilter类继承自RGBImageFilter,它的构造函数要求传入原始图象的宽度和高度。该类实现了filterRGB抽象函数,缺省的方式下,该函数将x,y所标识的象素的ARGB值传入,程序员按照一定的程序逻辑处理后返回该象素新的ARGB值
this.width=width;
this.height=height;
this.alpha=alpha;
}

public int filterRGB(int x,int y,int rgb) {
DirectColorModel dcm=(DirectColorModel)ColorModel.getRGBdefault();
//DirectColorModel类用来将ARGB值独立分解出来
int red=dcm.getRed(rgb);
int green=dcm.getGreen(rgb);
int blue=dcm.getBlue(rgb);
if(red==255&&green==255&&blue==255)//如果像素为白色,则让它透明
alpha=0;
return alpha<<24|red<<16|green<<8|blue;//进行标准ARGB输出以实现图象过滤
}
} [@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/9650775/viewspace-924263/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/9650775/viewspace-924263/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值