Here you can find the source of generateTexturePaint(String text, Font font, Color textColor, Color bgColor, int width, int height)
Parameter | Description |
---|---|
text | the text to display in the texture paint |
font | the font to use for the text |
textColor | the text color |
bgColor | the background color |
width | the width of the texture |
height | the height of the texture |
public static Paint generateTexturePaint(String text, Font font, Color textColor, Color bgColor, int width, int height)
//package com.java2s; /* Copyright (c) 2011 Danish Maritime Authority. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License./*from w w w. j a v a 2 s. c o m*/ */ import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import java.awt.TexturePaint; import java.awt.image.BufferedImage; public class Main { /** * Generates a {@linkplain TexturePaint} of the given size, using * the given text as a pattern. * * @param text the text to display in the texture paint * @param font the font to use for the text * @param textColor the text color * @param bgColor the background color * @param width the width of the texture * @param height the height of the texture * @return the texture paint */ public static Paint generateTexturePaint(String text, Font font, Color textColor, Color bgColor, int width, int height) { BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bi.createGraphics(); g2.setColor(bgColor); g2.fillRect(0, 0, width, height); g2.setColor(textColor); g2.setFont(font); // Draw the text centered in the bitmap FontMetrics fm = g2.getFontMetrics(); g2.drawString(text, (width - fm.stringWidth(text)) / 2, fm.getAscent() + (height - (fm.getAscent() + fm.getDescent())) / 2); return new TexturePaint(bi, new Rectangle(0, 0, width, height)); } }