Java基础 awt Graphics2D 生成矩形图片并向其中画一条直线

时间:2023-03-09 06:40:59
Java基础 awt Graphics2D 生成矩形图片并向其中画一条直线
  •     JDK :OpenJDK-11
  •      OS :CentOS 7.6.1810
  •      IDE :Eclipse 2019‑03
  • typesetting :Markdown

code

package per.jizuiku.gui;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import javax.imageio.ImageIO; /**
* @author 给最苦
* @date 2019/06/30
* @blog www.cnblogs.com/jizuiku
*/
public class Demo { /**
* @param args
*/
public static void main(String[] args) {
try {
getImage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } /**
*
* @throws FileNotFoundException
* @throws IOException
*/
public static void getImage() throws FileNotFoundException, IOException {
// 得到图片缓冲区
int width = 100;
int height = 50;
int imageType = BufferedImage.TYPE_INT_BGR;
BufferedImage myImage = new BufferedImage(width, height, imageType); // 得到画笔
Graphics2D pen = (Graphics2D)myImage.getGraphics(); // 设置笔的颜色,即背景色
pen.setColor(Color.WHITE); // 画出一个矩形
// 坐标x 坐标y 宽度100 长度50
pen.fillRect(0, 0, 100, 50); // 字的颜色 和 背景的颜色 要不同的
pen.setColor(Color.blue); // 划线
// 点动成线,线动成面,面动成体
// 两点确定一条直线
int xStart = 5;
int yStart = 15;
int xEnd = 60;
int yEnd = 30; // 设置线的宽度
float lineWidth = 7F;
pen.setStroke(new BasicStroke(lineWidth)); pen.drawLine(xStart, yStart, xEnd, yEnd); ImageIO.write(myImage, "JPEG", new FileOutputStream("line" + ".jpg")); } }

result

Java基础 awt Graphics2D 生成矩形图片并向其中画一条直线

sourceCode

/**
* Draws a line, using the current color, between the points
* <code>(x1,&nbsp;y1)</code> and <code>(x2,&nbsp;y2)</code>
* in this graphics context's coordinate system.
* @param x1 the first point's <i>x</i> coordinate.
* @param y1 the first point's <i>y</i> coordinate.
* @param x2 the second point's <i>x</i> coordinate.
* @param y2 the second point's <i>y</i> coordinate.
*/
public abstract void drawLine(int x1, int y1, int x2, int y2);

resource

  • [ JDK ] openjdk.java.net
  • [ doc - 参考 ] docs.oracle.com/en/java/javase/11
  • [ 规范 - 推荐 ] yq.aliyun.com/articles/69327
  • [ 规范 - 推荐 ] google.github.io/styleguide
  • [ 源码 ] hg.openjdk.java.net
  • [ OS ] www.centos.org
  • [ IDE ] www.eclipse.org/downloads/packages
  • [ 平台 ] www.cnblogs.com


感谢帮助过 给最苦 的人们。

Java、Groovy和Scala等基于JVM的语言,优秀,值得学习。

规范的命名和代码格式等,有助于沟通和理解。

JVM的配置、监控与优化,比较实用,值得学习。