多彩文本的Java图形库 [英] Java graphic library for multicoloured text

查看:129
本文介绍了多彩文本的Java图形库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道推荐的用于处理Java中多色文本的库或过程。我当前使用的java.awt.Graphics,虽然函数,似乎有点复杂,比必要的。



主要问题涉及频繁更改颜色,创建一个新的java.awt.Colour()对象,每当需要新的颜色时(它通常不是预定义的值之一)。我已经记录了以前使用的rgb值,但可能颜色可能会更改为唯一值对于我绘制的每个字符:

  java.awt.Color colorRender = new java.awt.Color(rgb); 
g.setColor(colorRender);

我还在我的代码上运行了一个分析器,并在极端情况下确定了一个次要瓶颈。我怀疑它可能是用于绘制单个字符的方法,但是在确定所述字符时可能会有开销:

  char [] c = new char [1]; //创建一次用于多种用途
/ * ... * /
g.drawChars(charRender,0,1,x,y);

我已经看了BufferedImage类 - 虽然对于像素级图形来说非常棒,但它没有直接支持绘制字符。

解决方案

我假设您将文本呈现给任意组件(通过paintComponent()),而不是尝试修改JTextPane,JLabel或其他预先存在的小部件中的文本颜色。

如果是这种情况,您应该使用 AttributedString 以及 TextAttribute 。这些允许您为字符串中的各种字符范围指定不同的样式(颜色,字体等),然后使用Graphics.drawString(...)呈现整个字符串。这样,底层图形子系统将在渲染过程中处理对图形状态的任何必要更改,使您的代码更具可读性,并且可能会更快。

这里是一个示例用法。



当然,其他已经提到,你也应该缓存你的Color对象,而不是一遍又一遍地重新创建它们。


I would like to know the recommended library or procedure for dealing with multi-coloured text within Java. My current usage of java.awt.Graphics, while function, appears to be a bit more complex than necessary.

The main issue involves the frequent change of colour, creating a new java.awt.Colour() object whenever a new colour is needed (and it's usually not one of the predefined values.) I already keep track of the previously used rgb value, but it's possible that the colour can potentially change to unique values for each character I draw:

java.awt.Color colorRender = new java.awt.Color(rgb);
g.setColor(colorRender);

I also ran a profiler on my code, and identified a secondary bottleneck in an extreme case. I suspect that it may be the method used for drawing a single character, but there may be overhead in determining said character:

char[] c = new char[1]; // Created once for many uses
/* ... */
g.drawChars(charRender, 0, 1, x, y);

I have looked at the BufferedImage class - while it's great for pixel-level graphics, it doesn't directly support drawing characters.

解决方案

I'm assuming you're rendering text to an arbitrary component (via paintComponent()) rather than trying to modify the color of text in a JTextPane, JLabel, or other pre-existing widget.

If this is the case, you should look into using an AttributedString along with TextAttribute. These allow you to assign different styles (color, font, etc.) to various ranges of characters within a string and then render the whole string using Graphics.drawString(...). This way, the underlying graphics subsystem will handle any necessary changes to the graphics state during rendering making your code much more readable, and probably faster.

Here is an example usage.

Of course, as other have mentioned, you should also be caching your Color objects rather than recreating them over and over.

这篇关于多彩文本的Java图形库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆