首页   >   代码编程

常用的java绘图api(一)

Graphics,是java中画图的对象,从它衍生出来的还有Graphics2D对象,既可以简单的写写字,也可以画一些图形,如:矩形、圆形、三角形、多边形,还有一些复杂的API可以实现炫酷的效果,如:旋转、渐变。

但是Swing这个东西现在用的并不多了,所以Java绘图也用的不多,最近无意中翻到了在之前公司做过的一个画图的项目,也有写过博客做分享(http://www.zuidaima.com/share/2457951855217664.htm),今天来整理一些常用的绘图API。

setColor:设置画笔颜色

getColor:获取画笔颜色

/**
 * Gets this graphics context's current color.
 * @return    this graphics context's current color.
 * @see       java.awt.Color
 * @see       java.awt.Graphics#setColor(Color)
 */
public abstract Color getColor();
/**
 * Sets this graphics context's current color to the specified
 * color. All subsequent graphics operations using this graphics
 * context use this specified color.
 * @param     c   the new rendering color.
 * @see       java.awt.Color
 * @see       java.awt.Graphics#getColor
 */
public abstract void setColor(Color c);

setFont:设置字体大小

getFont:获取字体大小

/**
 * Gets the current font.
 * @return    this graphics context's current font.
 * @see       java.awt.Font
 * @see       java.awt.Graphics#setFont(Font)
 */
public abstract Font getFont();
/**
 * Sets this graphics context's font to the specified font.
 * All subsequent text operations using this graphics context
 * use this font. A null argument is silently ignored.
 * @param  font   the font.
 * @see     java.awt.Graphics#getFont
 * @see     java.awt.Graphics#drawString(java.lang.String, int, int)
 * @see     java.awt.Graphics#drawBytes(byte[], int, int, int, int)
 * @see     java.awt.Graphics#drawChars(char[], int, int, int, int)
*/
public abstract void setFont(Font font);

setStroke:设置画笔粗细(绘制图形时用到,绘制文字不生效)

/**
 * Sets the <code>Stroke</code> for the <code>Graphics2D</code> context.
 * @param s the <code>Stroke</code> object to be used to stroke a
 * <code>Shape</code> during the rendering process
 * @see BasicStroke
 * @see #getStroke
 */
public abstract void setStroke(Stroke s);

translate:坐标位置移动

/**
 * Translates the origin of the <code>Graphics2D</code> context to the
 * point (<i>x</i>,&nbsp;<i>y</i>) in the current coordinate system.
 * Modifies the <code>Graphics2D</code> context so that its new origin
 * corresponds to the point (<i>x</i>,&nbsp;<i>y</i>) in the
 * <code>Graphics2D</code> context's former coordinate system.  All
 * coordinates used in subsequent rendering operations on this graphics
 * context are relative to this new origin.
 * @param  x the specified x coordinate
 * @param  y the specified y coordinate
 * @since   JDK1.0
 */
public abstract void translate(int x, int y);

shear:倾斜

/**
 * Concatenates the current <code>Graphics2D</code>
 * <code>Transform</code> with a shearing transform.
 * Subsequent renderings are sheared by the specified
 * multiplier relative to the previous position.
 * This is equivalent to calling <code>transform(SH)</code>, where SH
 * is an <code>AffineTransform</code> represented by the following
 * matrix:
 * <pre>
 *          [   1   shx   0   ]
 *          [  shy   1    0   ]
 *          [   0    0    1   ]
 * </pre>
 * @param shx the multiplier by which coordinates are shifted in
 * the positive X axis direction as a function of their Y coordinate
 * @param shy the multiplier by which coordinates are shifted in
 * the positive Y axis direction as a function of their X coordinate
 */
public abstract void shear(double shx, double shy);

rotate:旋转

/**
 * Concatenates the current <code>Graphics2D</code>
 * <code>Transform</code> with a rotation transform.
 * Subsequent rendering is rotated by the specified radians relative
 * to the previous origin.
 * This is equivalent to calling <code>transform(R)</code>, where R is an
 * <code>AffineTransform</code> represented by the following matrix:
 * <pre>
 *          [   cos(theta)    -sin(theta)    0   ]
 *          [   sin(theta)     cos(theta)    0   ]
 *          [       0              0         1   ]
 * </pre>
 * Rotating with a positive angle theta rotates points on the positive
 * x axis toward the positive y axis.
 * @param theta the angle of rotation in radians
 */
public abstract void rotate(double theta);

drawString:绘制文字

/**
 * Renders the text of the specified <code>String</code>, using the
 * current text attribute state in the <code>Graphics2D</code> context.
 * The baseline of the
 * first character is at position (<i>x</i>,&nbsp;<i>y</i>) in
 * the User Space.
 * The rendering attributes applied include the <code>Clip</code>,
 * <code>Transform</code>, <code>Paint</code>, <code>Font</code> and
 * <code>Composite</code> attributes.  For characters in script
 * systems such as Hebrew and Arabic, the glyphs can be rendered from
 * right to left, in which case the coordinate supplied is the
 * location of the leftmost character on the baseline.
 * @param str the string to be rendered
 * @param x the x coordinate of the location where the
 * <code>String</code> should be rendered
 * @param y the y coordinate of the location where the
 * <code>String</code> should be rendered
 * @throws NullPointerException if <code>str</code> is
 *         <code>null</code>
 * @see         java.awt.Graphics#drawBytes
 * @see         java.awt.Graphics#drawChars
 * @since       JDK1.0
 */
public abstract void drawString(String str, int x, int y);

drawRect:绘制矩形

/**
 * Draws the outline of the specified rectangle.
 * The left and right edges of the rectangle are at
 * <code>x</code> and <code>x&nbsp;+&nbsp;width</code>.
 * The top and bottom edges are at
 * <code>y</code> and <code>y&nbsp;+&nbsp;height</code>.
 * The rectangle is drawn using the graphics context's current color.
 * @param         x   the <i>x</i> coordinate
 *                         of the rectangle to be drawn.
 * @param         y   the <i>y</i> coordinate
 *                         of the rectangle to be drawn.
 * @param         width   the width of the rectangle to be drawn.
 * @param         height   the height of the rectangle to be drawn.
 * @see          java.awt.Graphics#fillRect
 * @see          java.awt.Graphics#clearRect
 */
public void drawRect(int x, int y, int width, int height);

draw3DRect:绘制3D矩形,其实就是坐标做了稍微的移动,造成视觉上的高低不平,从而形成3D的感觉

/**
 * Draws a 3-D highlighted outline of the specified rectangle.
 * The edges of the rectangle are highlighted so that they
 * appear to be beveled and lit from the upper left corner.
 * <p>
 * The colors used for the highlighting effect are determined
 * based on the current color.
 * The resulting rectangle covers an area that is
 * <code>width&nbsp;+&nbsp;1</code> pixels wide
 * by <code>height&nbsp;+&nbsp;1</code> pixels tall.
 * @param       x the <i>x</i> coordinate of the rectangle to be drawn.
 * @param       y the <i>y</i> coordinate of the rectangle to be drawn.
 * @param       width the width of the rectangle to be drawn.
 * @param       height the height of the rectangle to be drawn.
 * @param       raised a boolean that determines whether the rectangle
 *                      appears to be raised above the surface
 *                      or sunk into the surface.
 * @see         java.awt.Graphics#fill3DRect
 */
public void draw3DRect(int x, int y, int width, int height, boolean raised);

drawRoundRect:绘制圆角矩形

/**
 * Draws an outlined round-cornered rectangle using this graphics
 * context's current color. The left and right edges of the rectangle
 * are at <code>x</code> and <code>x&nbsp;+&nbsp;width</code>,
 * respectively. The top and bottom edges of the rectangle are at
 * <code>y</code> and <code>y&nbsp;+&nbsp;height</code>.
 * @param      x the <i>x</i> coordinate of the rectangle to be drawn.
 * @param      y the <i>y</i> coordinate of the rectangle to be drawn.
 * @param      width the width of the rectangle to be drawn.
 * @param      height the height of the rectangle to be drawn.
 * @param      arcWidth the horizontal diameter of the arc
 *                    at the four corners.
 * @param      arcHeight the vertical diameter of the arc
 *                    at the four corners.
 * @see        java.awt.Graphics#fillRoundRect
 */
public abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight);

clearRect:清除矩形,可以看做一个清除画布的方法,不单单是清除矩形

/**
 * Clears the specified rectangle by filling it with the background
 * color of the current drawing surface. This operation does not
 * use the current paint mode.
 * <p>
 * Beginning with Java&nbsp;1.1, the background color
 * of offscreen images may be system dependent. Applications should
 * use <code>setColor</code> followed by <code>fillRect</code> to
 * ensure that an offscreen image is cleared to a specific color.
 * @param       x the <i>x</i> coordinate of the rectangle to clear.
 * @param       y the <i>y</i> coordinate of the rectangle to clear.
 * @param       width the width of the rectangle to clear.
 * @param       height the height of the rectangle to clear.
 * @see         java.awt.Graphics#fillRect(int, int, int, int)
 * @see         java.awt.Graphics#drawRect
 * @see         java.awt.Graphics#setColor(java.awt.Color)
 * @see         java.awt.Graphics#setPaintMode
 * @see         java.awt.Graphics#setXORMode(java.awt.Color)
 */
public abstract void clearRect(int x, int y, int width, int height);

drawPolygon:绘制多边形,根据传递进来的坐标依次连线,最后组成多边形,如果nPoints参数小于前面两个数组的长度,那么前面的数组会被nPoints参数截断,比如:想绘制一个6边形,但是最后一参数是3,那么最终就是一个三角形

/**
 * Draws a closed polygon defined by
 * arrays of <i>x</i> and <i>y</i> coordinates.
 * Each pair of (<i>x</i>,&nbsp;<i>y</i>) coordinates defines a point.
 * <p>
 * This method draws the polygon defined by <code>nPoint</code> line
 * segments, where the first <code>nPoint&nbsp;-&nbsp;1</code>
 * line segments are line segments from
 * <code>(xPoints[i&nbsp;-&nbsp;1],&nbsp;yPoints[i&nbsp;-&nbsp;1])</code>
 * to <code>(xPoints[i],&nbsp;yPoints[i])</code>, for
 * 1&nbsp;&le;&nbsp;<i>i</i>&nbsp;&le;&nbsp;<code>nPoints</code>.
 * The figure is automatically closed by drawing a line connecting
 * the final point to the first point, if those points are different.
 * @param        xPoints   a an array of <code>x</code> coordinates.
 * @param        yPoints   a an array of <code>y</code> coordinates.
 * @param        nPoints   a the total number of points.
 * @see          java.awt.Graphics#fillPolygon
 * @see          java.awt.Graphics#drawPolyline
 */
public abstract void drawPolygon(int xPoints[], int yPoints[], int nPoints);

drawOval:绘制圆形

/**
 * Draws the outline of an oval.
 * The result is a circle or ellipse that fits within the
 * rectangle specified by the <code>x</code>, <code>y</code>,
 * <code>width</code>, and <code>height</code> arguments.
 * <p>
 * The oval covers an area that is
 * <code>width&nbsp;+&nbsp;1</code> pixels wide
 * and <code>height&nbsp;+&nbsp;1</code> pixels tall.
 * @param       x the <i>x</i> coordinate of the upper left
 *                     corner of the oval to be drawn.
 * @param       y the <i>y</i> coordinate of the upper left
 *                     corner of the oval to be drawn.
 * @param       width the width of the oval to be drawn.
 * @param       height the height of the oval to be drawn.
 * @see         java.awt.Graphics#fillOval
 */
public abstract void drawOval(int x, int y, int width, int height);

drawArc:绘制弧形,跟drawOval非常像,如果后两个参数传的是0和360,那么最终出来的图形也是一个圆形

/**
 * Draws the outline of a circular or elliptical arc
 * covering the specified rectangle.
 * <p>
 * The resulting arc begins at <code>startAngle</code> and extends
 * for <code>arcAngle</code> degrees, using the current color.
 * Angles are interpreted such that 0&nbsp;degrees
 * is at the 3&nbsp;o'clock position.
 * A positive value indicates a counter-clockwise rotation
 * while a negative value indicates a clockwise rotation.
 * <p>
 * The center of the arc is the center of the rectangle whose origin
 * is (<i>x</i>,&nbsp;<i>y</i>) and whose size is specified by the
 * <code>width</code> and <code>height</code> arguments.
 * <p>
 * The resulting arc covers an area
 * <code>width&nbsp;+&nbsp;1</code> pixels wide
 * by <code>height&nbsp;+&nbsp;1</code> pixels tall.
 * <p>
 * The angles are specified relative to the non-square extents of
 * the bounding rectangle such that 45 degrees always falls on the
 * line from the center of the ellipse to the upper right corner of
 * the bounding rectangle. As a result, if the bounding rectangle is
 * noticeably longer in one axis than the other, the angles to the
 * start and end of the arc segment will be skewed farther along the
 * longer axis of the bounds.
 * @param        x the <i>x</i> coordinate of the
 *                    upper-left corner of the arc to be drawn.
 * @param        y the <i>y</i>  coordinate of the
 *                    upper-left corner of the arc to be drawn.
 * @param        width the width of the arc to be drawn.
 * @param        height the height of the arc to be drawn.
 * @param        startAngle the beginning angle.
 * @param        arcAngle the angular extent of the arc,
 *                    relative to the start angle.
 * @see         java.awt.Graphics#fillArc
 */
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle);

copyArea:复制区域,(0, 0)对应原图形的左上角

/**
 * Copies an area of the component by a distance specified by
 * <code>dx</code> and <code>dy</code>. From the point specified
 * by <code>x</code> and <code>y</code>, this method
 * copies downwards and to the right.  To copy an area of the
 * component to the left or upwards, specify a negative value for
 * <code>dx</code> or <code>dy</code>.
 * If a portion of the source rectangle lies outside the bounds
 * of the component, or is obscured by another window or component,
 * <code>copyArea</code> will be unable to copy the associated
 * pixels. The area that is omitted can be refreshed by calling
 * the component's <code>paint</code> method.
 * @param       x the <i>x</i> coordinate of the source rectangle.
 * @param       y the <i>y</i> coordinate of the source rectangle.
 * @param       width the width of the source rectangle.
 * @param       height the height of the source rectangle.
 * @param       dx the horizontal distance to copy the pixels.
 * @param       dy the vertical distance to copy the pixels.
 */
public abstract void copyArea(int x, int y, int width, int height, int dx, int dy);

setPaint:设置绘制图形的渲染方式,例如:渐变(GradientPaint)

/**
 * Sets the <code>Paint</code> attribute for the
 * <code>Graphics2D</code> context.  Calling this method
 * with a <code>null</code> <code>Paint</code> object does
 * not have any effect on the current <code>Paint</code> attribute
 * of this <code>Graphics2D</code>.
 * @param paint the <code>Paint</code> object to be used to generate
 * color during the rendering process, or <code>null</code>
 * @see java.awt.Graphics#setColor
 * @see #getPaint
 * @see GradientPaint
 * @see TexturePaint
 */
public abstract void setPaint( Paint paint );

注意

1、与draw方法相对应的还有fill方法,前者是绘制图形,只有边框;后者是填充图形,无边框;

2、绘图尽量使用Graphics2D对象,有API可以去除锯齿,让图形显得更加平滑;

// 消除画图锯齿
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 消除文字锯齿
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

最后,自己写一段代码来看一下效果(只求了解API,不求美观):

package feiqq.ui.frame;

import javax.swing.*;
import java.awt.*;

/**
 * Created by SongFei on 2019/3/21.
 */
public class TestFrame extends JFrame {

    public TestFrame() {
        super();
        initGUI();
    }

    private void initGUI() {
        // 设置窗体大小
        setSize(600, 600);
        // 设置关闭方式
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        // 设置窗体打开处于屏幕中央
        setLocationRelativeTo(null);
        // 设置窗体可见
        setVisible(true);

        // 默认的内容Container,可以自己替换掉
//        getContentPane();

        // 自定义内容面板
        final JPanel contentPane = new JPanel() {
            @Override
            public void paint(Graphics g) {

                Graphics2D g2 = (Graphics2D) g;

                g2.setColor(Color.ORANGE);

                // 消除画图锯齿
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                // 消除文字锯齿
                g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

                // 坐标移动
                g2.translate(10, 10);

                // 画弧形,可以用作百分比,也可以用来画圆
                g2.fillArc(0, 200, 100, 100, 0, 100);

                // 画圆形
                g2.fillOval(0, 300, 100, 100);

                // 绘制3D矩形
                g2.fill3DRect(100, 100, 100, 100, true);

                // 画矩形,可以设定边框弧度
                g2.fillRoundRect(200, 200, 100, 100, 50, 50);

                // 绘制矩形
                g2.fillRect(300, 300, 100, 100);

                // 在原来的基础上进行复制,(0,0)是原图的左上角
                g2.copyArea(300, 300, 100, 100, 100, 0);

                // 画一个多边形,指定好多边形的几个坐标点进行连接
                // 最后一个参数,如果传少了,后面的坐标就会被舍弃
                g2.drawPolygon(new int[]{100, 200, 250, 150, 50}, new int[]{100, 100, 200, 300, 200}, 5);

                g2.setFont(new Font("微软雅黑", Font.PLAIN, 50));
                g2.shear(0.1, 0.5);

                g2.setPaint(new GradientPaint(150, 100, Color.GREEN, 200, 100, Color.BLUE, true));
                g2.drawString("hello world", 100, 100);
                g2.rotate(1.5);

                // 设置画笔粗细
                g2.setStroke(new BasicStroke(30));
                g2.drawOval(100, 100, 100, 100);
            }
        };
        // 空布局,个人感觉更好控制
        contentPane.setLayout(null);
        // 设置边框
        // contentPane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
        // 替换默认的Container
        setContentPane(contentPane);
    }

    public static void main(String[] args) {
        new TestFrame();
    }

}

效果图如下:

常用的java绘图api(一)

QQ群Ⅰ: 686430774 (已满)

QQ群Ⅱ: 718410762 (已满)

QQ群Ⅲ: 638620451 (已满)

QQ群Ⅳ: 474195684

如果文章有帮到你,可以考虑请博主喝杯咖啡!

分享到:

欢迎分享本文,转载请注明出处!

作者:不忘初心

发布时间:2019-03-24

永久地址:https://www.jiweichengzhu.com/article/fdf7ca41dd264a259600d8fe6bf7561b

评论