#java #string #image #graphics2d #drawstring
Вопрос:
У меня есть код, который вставляет несколько строк в изображение. Я хотел бы, чтобы на разрыве линии была линия каждого цвета, например, серая линия и черная линия…
Изображение, сгенерированное в этот момент, содержит все линии одного цвета (серого), в идеале оно содержит серую линию и черную линию.
public static void addTextWatermark(String text, String type, File source, File destination) throws IOException { BufferedImage image = ImageIO.read(source); // determine image type and handle correct transparency int imageType = "png".equalsIgnoreCase(type) ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB; BufferedImage watermarked = new BufferedImage(image.getWidth(), image.getHeight(), imageType); // initializes necessary graphic properties Graphics2D w = (Graphics2D) watermarked.getGraphics(); AffineTransform aft = new AffineTransform(); aft.rotate(Math.toRadians(45), 0, 0); w.drawImage(image, 0, 0, null); AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f); w.setComposite(alphaChannel); w.setColor(Color.GRAY); Font font = new Font(Font.SANS_SERIF, Font.BOLD, 18); //TODO: calcular proporcao da imagem com o tamanho da font if(image.getWidth() gt; 1000) { font = new Font(Font.SANS_SERIF, Font.BOLD, 30); } w.setFont(font.deriveFont(aft)); //w.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14)); FontMetrics fontMetrics = w.getFontMetrics(); Rectangle2D rect = fontMetrics.getStringBounds(text, w); ////////////////////////////// var xFactor = Math.cos(45 * Math.PI / 180) - 0.4; var yFactor = Math.sin(45 * Math.PI / 180); log.info("==== xFactor: " xFactor); log.info("==== yFactor: " yFactor); for (var x = 0; x lt; image.getWidth(); x = rect.getWidth() * xFactor rect.getHeight() * yFactor) { for (var y = -60 * yFactor; y lt; image.getHeight(); y = rect.getWidth() * yFactor rect.getHeight() * xFactor) { //w.drawString(text, x, (int) y); w.drawString(text, x, (int) y); } } ///////////////////////////// // calculate center of the image //int centerX = (image.getWidth() - (int) rect.getWidth()) / 2; //int centerY = image.getHeight() / 2; // add text overlay to the image // w.drawString(text, centerX, centerY); ImageIO.write(watermarked, type, destination); w.dispose(); }
Созданное изображение:
Комментарии:
1. Если вам нужен текст другого цвета, вам нужно будет вызвать метод setColor(…) для каждой строки текста.