How to determine the length of a graphic string? - java

I'm creating a graphical timeline out of an excel document and I need to have small tags of the name of the event next to the marker for that event. Some of these are easy and are right justified but others are left justified and I need to figure out their width so that I can properly offset them.
window.drawString("7/4-Fourth of July",horizontalIndex-Offset,verticalIndex);
Currently I'm averaging the pixel width using an average of both font sizes 10 and 32, but this doesn't really cut it. Can someone help me get the exact offset?

This thread explains how to do it:
Calculate the display width of a string in Java
You should first get the font metrics, and then ask the metrics how wide a certain string is.

from a java.awt.Graphics object, you can call getFontMetrics. the FontMetrics object has a getStringBounds method that does what you need.
here's the documentation

and another good alternative is SwingUtilities#computeStringWidth(FontMetrics fm, String str)

As a (read: my ;-) general rule, never use the Graphics-level drawString methods. Instead, use a JLabel/CellRendererPane pair to "stamp" the text onto whatever component.
The advantages
anti-alias is handled automagically
size calculations are done in the labels' bowels, so positioning calculations dont require any low-level methods but simply based on the labels' prefSize

TextLayout, shown here, is another alternative.

Related

Detecting if a BufferedImage contains transparent pixels

I'm trying to optimise a rendering engine in Java to not draw object's which are covered up by 'solid' child objects drawn in front of them, i.e. the parent is occluded by its children.
I'm wanting to know if an arbitrary BufferedImage I load in from a file contains any transparent pixels - as this affects my occlusion testing.
I've found I can use BufferedImage.getColorModel().hasAlpha() to find if the image supports alpha, but in the case that it does, it doesn't tell me if it definitely contains non-opaque pixels.
I know I could loop over the pixel data & test each one's alpha value & return as soon as I discover a non-opaque pixel, but I was wondering if there's already something native I could use, a flag that is set internally perhaps? Or something a little less intensive than iterating through pixels.
Any input appreciated, thanks.
Unfortunately, you will have to loop through each pixel (until you find a transparent pixel) to be sure.
If you don't need to be 100% sure, you could of course test only some pixels, where you think transparency is most likely to occur.
By looking at various images, I think you'll find that most images that has transparent parts contains transparency along the edges. This optimization will help in many common cases.
Unfortunately, I don't think that there's an optimization that can be done in one of the most common cases, the one where the color model allows transparency, but there really are no transparent pixels... You really need to test every pixel in this case, to know for sure.
Accessing the alpha values in its "native representation" (through the Raster/DataBuffer/SampleModel classes) is going to be faster than using BufferedImage.getRGB(x, y) and mask out the alpha values.
I'm pretty sure you'll need to loop through each pixel and check for an Alpha value.
The best alternative I can offer is to write a custom method for reading the pixel data - ie your own Raster. Within this class, as you're reading the pixel data from the source file into the data buffer, you can check for the alpha values as you go. Of course, this isn't much help if you're using a built-in image reading class, and involves a lot more effort.

Changing the min and max value of JSlider depanding on condition

I'm creating a Swing GUI in Netbeans. The purpose of this GUI is to open an (buffered)image (in a JLabel as icon) and apply Affine transforms on it. Now there are 4 transforms that I'm doing as follows.
Now, each transform requires two sliders to change the X and Y value, except that of rotate, which will require only one. I did it this way since its much better than having to do four tabs for all 4 types of transforms. Also I want it to be such that , for example, if an image is rotated, the same rotated image can be sheared by selecting shear from the Drop down list.
The problem is (are):
How do i repaint the label icon and apply different transform on the same repainted image?
Also, how do i change the minimum and maximum value of JSlider depanding on the effect selected?
You should store originally loaded BufferedImage, and create its copy - that way you won't "destroy" it.
As for the changing value there are methods setMaximum and setMinimum - add listener to list, as stated in Oracle tutorial and modify the values.
As a concrete example of #Daniel's answer, the article Image processing with Java 2D describes the program ImageDicer. It constructs a TreeMap<String, BufferedImageOp> each of which may be selected from a JComboBox and applied to a BufferedImage.
See also related examples here and here.

Android fuzzy / faded fonts possible?

So I am developing a very simple app, mostly for personal use, am am looking for a simple solution to a simple problem.
In its simplest form I am looking for a way to have a line of text with just one or two words blurred out. Basically I am looking to blur text beyond readability but still hinting at what is hidden. Kind of a knowledge / memory app to help memorize some definitions by prompting with a few key words.
I am having issues finding a simple way to accomplish this. Am I just missing an attribute to blur text?
I have thought about:
overriding say the textview onDraw but that seems overkill and I am unsure if there are any methods available to easily blur text.
using the toHtml and trying out the new CSS3 blur effects but I don't think that that is a reasonable solution and I am not sure that the Android platform supports all the CSS3 format, if any.
the simplest and most desirable solution in my book was to find a font (ttf, off, etc) file, derived from a common font, that is already blurred as I described, and use that alternating with the non blurred version of that font to achieve the desired effect.
make the described font but that just plain requires too much time on my part and the outcome is not necessarily good :)
I have thought about some alternative ways to simulate this effect but they all result in fading the text, which is undesirable, since I want to have some visual prompts to indicate the obscured texts length.
Any ideas? It's been years since I have developed in Java and I am unsure what is available and what the Android OS supports.
I haven't looked into using these properties for only part of the text, but TextView has some possibly useful properties related to text shadows. Using something like the following XML attributes, you could hide the actual text and just show a blurred shadow.
android:textColor - #0000 (fully transparent so that the crisp text is not shown)
android:shadowColor - #FFFF (or whatever color you want to appear)
android:shadowDx - 0 (the shadow is in the same horizontal position as the text)
android:shadowDy - 0 (the shadow is in the same vertical position as the text)
android:shadowRadius - Depends on how much you want to blur. A very small non-zero value, such as 0.001, will be sharp. Larger values blur more, and at some point the shadow becomes illegible.

Calculation of required display space for different subclasses of JComponent

For my current project i am writing a JTable based GUI. One of the main features is the ability to adjust the sizes of all cells at runtime, depending on the contents (which change over time). Currently all cells have the same height and width, when the application is started. I would like to change that to a more sophisticated approach. I was wondering if it would be somehow possible to determine the space needed by "the content" to be displayed properly. That is without to much empty space or cutting something of.
"The content" is a string for starters. It is loaded from a database and i can't make any assumptions whatsoever about it. It may be null. In this case there should be any kind of default size for the corresponding cell.
In the long run there will be all different kinds of content to be displayed, like pictures, video and so on.
I tried working with FontMetrics to calculate the length of the strings. But since i'm using JTextPanes to display them, i can't get it to work exactly. I think this has to do with JTextPanes automatic word wrapping because sometimes the lines aren't filled up. This screws up my calculations.
Well long story short: I need some kind of design guideline to achieve the feature descriped above. I'm sure one of you clever guys knows just how to do it.
Thanks in advance,
DeKay
Maybe the text pane size calculation in this How can I measure/calculate the size a Document needs to render itself? will help you out.
As you are using JTextPane for rendering, you may find this Q&A helpful.
The conversion textPane.modelToView() always comes out to null.
Note that modelToView "Returns: the coordinates as a rectangle ... or null if the component does not yet have a positive size."
I have still no idea, how to calculate the amount of space needed in general.
IIUC, the key to understanding #camickr's example is the use of setPreferredSize() to include the text pane's changed boundary, followed by validate() which "is used to cause a container to lay out its subcomponents again."
To set the height of a row in a JTable, look at here:
public void setRowHeight(int row, int rowHeight)
To set a column width, you have to look at the TableCOlumn API here:
public void setWidth(int width)
Hope this can help

Find an Image within an Image

I am looking for the best way to detect an image within another image. I have a small image and would like to find the location that it appears within a larger image - which will actually be screen captures. Conceptually, it is like a 'Where's Waldo?' sort of search in the larger image.
Are there any efficient/quick ways to accomplish this? Speed is more important than memory.
Edit:
The 'inner' image may not always have the same scale but will have the same rotation.
It is not safe to assume that the image will be perfectly contained within the other, pixel for pixel.
Wikipedia has an article on Template Matching, with sample code.
(While that page doesn't handle changed scales, it has links to other styles of matching, for example Scale invariant feature transform)
If rotation also had to be catered for, the Generalised Hough Transform can be used.
You can treat this as a substring problem, where characters in the alphabet are pixels and your string is the image. You would need also to use a special character in a similar vein to a linebreak, to denote the image boundary.
The algorithm you want is on wikipedia: http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
Update: If you cannot assume that the image is perfectly contained within the other, pixel for pixel, then this approach will not work.
There are other, more complicated algorithms based on the same dynamic programming concept as the above, but I won't go into them unless it's necessary.

Categories

Resources