用java代码模拟一张图片可以这样操作:1.创建BufferedImage类
普洱ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18980820575(备注:SSL证书合作)期待与您的合作!
2.根据BufferedImage类得到一个Graphics2D对象
3.根据Graphics2D对象进行逻辑操作
4.处理绘图
5.将绘制好的图片写入到图片
package com.graphics;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends JFrame {
public Test(){
getContentPane().add(new GJpanel());
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Test();
}
}
class GJpanel extends JPanel {
private int w;
private int h;
public GJpanel(){
}
public void paintComponent(final Graphics g){
w = getWidth();
h = getHeight();
g.setColor(Color.green);
g.drawLine(0, 0, 0,getHeight());
g.setColor(Color.red);
g.drawLine(0,h/2,w,h/2); //x
g.drawLine(w, h/2, w-10, h/2-10);
g.drawLine(w, h/2, w-10, h/2+10);
g.drawLine(w/2, 0,w/2, h); //y
g.drawLine(w/2, 0, w/2-10, 10);
g.drawLine(w/2, 0, w/2+10, 10);
g.drawString("Y", w/2-20, 20);
g.drawString("X", w-20, h/2+20);
for(int x =0;xw; x++){
int y =(int) (Math.cos (x*Math. PI/180)*h/3);
g.drawString("·", x, h/2-y);
}
}
}
这个是双缓冲的绘制方法
if (offScreenImage == null)
{
offScreenImage = this.createImage(GAME_WIDTH, GAME_HEIGHT);
}
这里是先在内存中创建一个 offScreenImage 的缓冲图像
gOffScreen.drawImage(imgs, 0, 0, GAME_WIDTH, GAME_HEIGHT,null);
这里是将背景图片绘制到刚才创建的这块缓冲区上
paint(gOffScreen);
g.drawImage(offScreenImage, 0, 0, null);
这里是将缓冲区再绘制到实际屏幕上
采用双缓冲可以保证画面不会闪烁 因为图片的刷新都是发生在内存区上的 实际屏幕上用户是感觉不出来的 所以人眼感觉不到闪烁
drawimage都是对Image对象处理,和组件的绘制一点关系也没;
把newImage的图再画到image里面去;
实例代码如下:
public class Tank extends JFrame {
private Image img = null;
boolean fi = false;
BufferedImage bi;
public Tank() {
this.addKeyListener(new KeyMonitor());
this.setBounds(300, 300, 300, 300);
this.setVisible(true);
this.setDefaultCloseOperation(Tank.EXIT_ON_CLOSE);
}
class KeyMonitor extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case 37: {
img = getToolkit().createImage("res/TankPic/pre.GIF");
fi = true;
System.out.println(img);
repaint();
break;
}
}
}
}
public void paint(Graphics g) {
super.paint(g);
bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB);
bi.getGraphics();
if (fi) {
g = img.getGraphics();
g.drawImage(bi, 50, 50, 40, 40, this);
}
}
public static void main(String[] args) {
new Tank();
}
}