日期:2014-05-20 浏览次数:20842 次
?
原贴链接:http://www.j2medev.com/bbs/dispbbs.asp?BoardID=19&ID=34799&replyID=&skin=1
?
目标效果图:
?
?
?
?
?
?
我的实现思路:
由于J2ME中无法setClip()为圆形,我们可以通过蒙板来实现。即填充一个纯色的圆形,然后通过遍历其像素并从原图相应位置提取像素,生成目标图形。
?
代码实现:
public class MyCanvas extends Canvas implements Runnable{
static final int FPS = 15;
static int screenW;
static int screenH;
static int midX;
static int midY;
private Image markImg;
private Graphics bg;
private Image backgroundImg;
private int x, y, r;
private final static int msp = 1; // 扩大速度
public MyCanvas(){
setFullScreenMode(true);
screenW = getWidth();
screenH = getHeight();
midX = screenW>>1;
midY = screenH>>1;
init();
statr();
}
private void statr() {
(new Thread(this)).start();
}
private void init() {
try {
backgroundImg = Image.createImage("/arc.png");
} catch (IOException e) {
e.printStackTrace();
}
x = midX;
y = midY;
r = 1;
}
protected void paint(Graphics g) {
// 清屏
g.setColor(0xffffff);
g.setClip(0, 0, screenW, screenH);
g.fillRect(0, 0, screenW, screenH);
// 背景底图
if(backgroundImg!=null)
g.drawImage(backgroundImg, midX, midY, Graphics.VCENTER|Graphics.HCENTER);
// 遮罩图层
if(markImg!=null)
g.drawImage(markImg, 0, 0, 20);
}
public void run() {
while(true){
long lastTime = System.currentTimeMillis();
update();
repaint();
serviceRepaints();
long takenTime = System.currentTimeMillis()-lastTime;
try {
if(takenTime<1000/FPS){
Thread.sleep(1000/FPS-takenTime);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void update(){
// 创建遮罩图
markImg = Image.createImage(screenW, screenH);
bg = markImg.getGraphics();
// 填充为白色
bg.setColor(0xffffff);
bg.fillRect(0, 0, screenW, screenH);
// 绘制一个绿色的圆(只要颜色能与背景有区别)
bg.setColor(0x00ff00);
bg.fillArc(x-r, y-r, r*2, r*2, 0, 360);
// 图片换色
markImg = changeColor(markImg, 0x00ff00, 0x00ffffff);
// 改变增量
r += msp;
if(r>(Math.max(screenW, screenH)>>1))
r = 1;
}
/**图片换色*/
private Image changeColor(Image img, int oldcolor, int newcolor){
int imgW = img.getWidth();
int imgH = img.getHeight();
int[] RGB = new int[imgW*imgH];
img.getRGB(RGB, 0, imgW, 0, 0, imgW, imgH);
// 需要改变的颜色
int oA = (oldcolor&0xff000000)>>24;
int oR = (oldcolor&0x00ff0000)>>16;
int oG = (oldcolor&0x0000ff00)>>8;
int oB = (oldcolor&0x000000ff);
// 目标颜色
int nA = (newcolor&0xff000000)>>24;
int nR = (newcolor&0x00ff0000)>>16;
int nG = (newcolor&0x0000ff00)>>8;
int nB = (newcolor&0x000000ff);
int size = RGB.length;
for(int i=size-1; i>=0; i--){
int A = (RGB[i]&0xff000000)>>24;
int R = (RGB[i]&0x00ff0000)>>16;
int G = (RGB[i]&0x0000ff00)>>8;
int B = (RGB[i]&0x000000ff);
if(A==oA&&R==oR&&G==oG&&B==oB){
RGB[i] = ((nA<<24)&0xff)|((nR<<16)&0xff)|((nG<<8)&0xff)|(nB&0xff);
}
}
img = Image.createRGBImage(RGB, imgW, imgH, true);
return img;
}
}