Reputation: 2296
I am presently running an automation UI test, part of the checks is to make sure the background color, font color and the font-family used are consistent throughout the app. The code takes a snapshot of screen or element and checks the background color, but I'm unable to check the font-family and font color. I have a code to check the background color, which works great. Is there a way to get the font-family and color? Is there any Java library that does that?
I have attached a sample image. The image background color is white that is detected by the code below.
This code checks the background-color
public void checkBackgroundColor(String mobileElement, String saveReadFile, String hexValue) throws IOException {
MobileElement elem = (MobileElement) getMobileDriver().findElement(By.xpath(mobileElement));
File scrFile = elem.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(saveReadFile));
File savedFile = new File(saveReadFile);
BufferedImage image = ImageIO.read( savedFile);
org.openqa.selenium.Point point = elem.getCenter();
org.openqa.selenium.Point location = elem.getLocation();
Dimension size = elem.getSize();
MyLogger.info("Point X is " + point.getX() +" Point Y is " + point.getY());
MyLogger.info("Location X is " + location.getX() +" Location Y is " + location.getY());
MyLogger.info("Size Height is " + size.getHeight() +" Size width is " + size.getWidth());
// Getting pixel color by position x and y
int h = (int) Math.round(size.getWidth() * 0.2);
int w = (int) Math.round(size.getHeight() * 0.8);
int clr= image.getRGB(h , w);
int r = (clr & 0x00ff0000) >> 16;
int g = (clr & 0x0000ff00) >> 8;
int b = clr & 0x000000ff;
String hex = String.format("#%02x%02x%02x", r, g, b);
if (hex.equalsIgnoreCase(hexValue)){
MyLogger.info("Actual value "+ hexValue +" of " +buttons+savedFile.getName() +" is equals to the expected value " +hex);
} else {
MyLogger.info("Actual value "+ hexValue +" of " +buttons+savedFile.getName() +" is is not equals to the expected value " +hex);
}
}
Upvotes: 0
Views: 349
Reputation: 6168
You can try this
Graphics g = image.getGraphics(); //using the BufferedImage from your example
System.out.println(g.getFont().getFamily()); // For me, it displays "Dialog" which is one of the logical fonts according to https://docs.oracle.com/javase/tutorial/2d/text/fonts.html
g.dispose();
UPDATE:
image.getGraphics()
doesn't return the Graphics2D
object that was used to create the overlay. It actually creates a new graphics object and returns it. Two of the subclasses of Graphics2D
actually hold a delegate object that apparently holds this info. Unfortunately, these subclasses of Graphics2D
are in the sun
package which is now restricted. Therefore, this information seems to be inaccessible. If you require the Font
that was used for the overlay, you may have no choice but to cache this information in some "overlay config" object.
Upvotes: 1