Java 怎么在指定位置绘制字符串

2019年8月20日22:39:40 评论 22

1.简介

Java 怎么在指定位置绘制字符串?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import java.awt.*;
import java.awt.geom.*;

public class Main {
    public static final int TEXT_TOPLEFT = 0;
    public static final int TEXT_TOP = 1;
    public static final int TEXT_TOPRIGHT = 2;
    public static final int TEXT_LEFT = 3;
    public static final int TEXT_CENTER = 4;
    public static final int TEXT_RIGHT = 5;
    public static final int TEXT_BOTTOMLEFT = 6;
    public static final int TEXT_BOTTOM = 7;
    public static final int TEXT_BOTTOMRIGHT = 8;

    public static void drawStringAt(String s, Font font, int xRef,
            int yRef, int aligned, Graphics context) {
        FontMetrics fm = context.getFontMetrics(font);
        Rectangle2D strBound = fm.getStringBounds(s, context);
        int xDraw, yDraw;
        if (aligned == TEXT_TOPLEFT) {
            xDraw = xRef;
            yDraw = yRef + (int) strBound.getHeight();
        } else if (aligned == TEXT_TOP) {
            xDraw = xRef - (int) strBound.getWidth() / 2;
            yDraw = yRef + (int) strBound.getHeight();
        } else if (aligned == TEXT_TOPRIGHT) {
            xDraw = xRef - (int) strBound.getWidth();
            yDraw = yRef + (int) strBound.getHeight();
        } else if (aligned == TEXT_LEFT) {
            xDraw = xRef;
            yDraw = yRef + (int) strBound.getHeight() / 2;
        } else if (aligned == TEXT_CENTER) {
            xDraw = xRef - (int) strBound.getWidth() / 2;
            yDraw = yRef + (int) strBound.getHeight() / 2;
        } else if (aligned == TEXT_RIGHT) {
            xDraw = xRef - (int) strBound.getWidth();
            yDraw = yRef + (int) strBound.getHeight() / 2;
        } else if (aligned == TEXT_BOTTOMLEFT) {
            xDraw = xRef;
            yDraw = yRef;
        } else if (aligned == TEXT_BOTTOM) {
            xDraw = xRef - (int) strBound.getWidth() / 2;
            yDraw = yRef;
        } else if (aligned == TEXT_BOTTOMRIGHT) {
            xDraw = xRef - (int) strBound.getWidth();
            yDraw = yRef;
        } else {
            
            xDraw = xRef;
            yDraw = yRef;
        }
        Font tmpFont = context.getFont();
        context.setFont(font);
        context.drawString(s, xDraw, yDraw);
        context.setFont(tmpFont); 
    }
}

 

3.总结

示例代码演示了 Java 怎么在指定位置绘制字符串,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: