public final class Graphics

  1. Object
  2. Graphics

Abstracts the underlying platform graphics context thus allowing us to achieve portability between MIDP devices and CDC devices. This abstaction simplifies and unifies the Graphics implementations of various platforms.

A graphics instance should never be created by the developer and is always accessed using either a paint callback or a mutable image. There is no supported way to create this object directly.

Fields

public static final int RENDERING_HINT_FAST = 1Rendering hint to indicate that the context should prefer to render primitives in a quick way, at the cost of quality, if there is an expensive operation.

Methods

protected void finalize()
public void translate(int x, int y)Translates the X/Y location for drawing on the underlying surface.
public int getTranslateX()Returns the current x translate value
public int getTranslateY()Returns the current y translate value
public int getColor()Returns the current color
public void setColor(int rgb)Sets the current rgb color while ignoring any potential alpha component within said color value.
public void setColor(Paint paint)Sets paint to be used for filling shapes.
public Paint getPaint()Gets the current Paint that is set to be used for filling shapes.
public int setAndGetColor(int rgb)Sets the current rgb color while ignoring any potential alpha component within said color value.
public Font getFont()Returns the font used with the drawString method calls
public void setFont(Font font)Sets the font to use with the drawString method calls
public int getClipX()Returns the x clipping position
public int[] getClip()Returns the clip as an x,y,w,h array
public void setClip(int[] clip)Sets the clip from an array containing x, y, width, height value
public void setClip(Shape shape)Clips the Graphics context to the Shape.
public int getClipY()Returns the y clipping position
public int getClipWidth()Returns the clip width
public int getClipHeight()Returns the clip height
public boolean isVisible(int x, int y, int w, int h)Returns true if the given rectangle (in the current Graphics coordinate space, with the active translation applied) intersects the current clip rectangle, i.e. anything drawn into it would be at least partially visible.
public void clipRect(int x, int y, int width, int height)Clips the given rectangle by intersecting with the current clipping region, this method can thus only shrink the clipping region and never increase it.
public void setClip(int x, int y, int width, int height)Updates the clipping region to match the given region exactly
public void pushClip()Pushes the current clip onto the clip stack.
public void popClip()Pops the top clip from the clip stack and sets it as the current clip.
public void drawLine(int x1, int y1, int x2, int y2)Draws a line between the 2 X/Y coordinates
public void fillRect(int x, int y, int width, int height)Fills the rectangle from the given position according to the width/height minus 1 pixel according to the convention in Java.
public void drawShadow(Image img, int x, int y, int offsetX, int offsetY, int blurRadius, int spreadRadius, int color, float opacity)Deprecated
public void clearRect(int x, int y, int width, int height)Clears rectangular area of the graphics context.
public void drawRect(int x, int y, int width, int height)Draws a rectangle in the given coordinates
public void drawRect(int x, int y, int width, int height, int thickness)Draws a rectangle in the given coordinates with the given thickness
public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)Draws a rounded corner rectangle in the given coordinates with the arcWidth/height matching the last two arguments respectively.
public void lighterColor(int factor)Makes the current color slightly lighter, this is useful for many visual effects
public void darkerColor(int factor)Makes the current color slightly darker, this is useful for many visual effects
public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)Fills a rounded rectangle in the same way as drawRoundRect
public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)Fills a circular or elliptical arc based on the given angles and bounding box.
public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)Draws a circular or elliptical arc based on the given angles and bounding box
public void drawString(String str, int x, int y, int textDecoration)Draw a string using the current font and color in the x,y coordinates.
public void drawStringBaseline(String str, int x, int y)Draws a string using baseline coordinates.
public void drawStringBaseline(String str, int x, int y, int textDecoration)Draws a string using baseline coordinates.
public void drawString(String str, int x, int y)Draw a string using the current font and color in the x,y coordinates.
public void drawChar(char character, int x, int y)Deprecated Draw the given char using the current font and color in the x,y coordinates.
public void drawChars(char[] data, int offset, int length, int x, int y)Deprecated Draw the given char array using the current font and color in the x,y coordinates.
public void drawImage(Image img, int x, int y)Draws the image so its top left coordinate corresponds to x/y
public boolean isRoundedImageSupported()Draws the image so its top left coordinate corresponds to x/y and scales it to width/height
public boolean isRoundedImageSupported(Image img)Whether drawImageRounded(Image, int, int, int, int, float) will round THIS image, which is the question a caller actually needs answered.
public void drawImageRounded(Image img, int x, int y, int w, int h, float cornerRadius)Draws an image with rounded corners, without building a rounded copy of it, on platforms that support it; elsewhere the image is drawn square.
public void drawImage(Image img, int x, int y, int w, int h)
public void drawShape(Shape shape, Stroke stroke)Draws a outline shape inside the specified bounding box.
public void fillShape(Shape shape)Fills the given shape using the current alpha and color settings.
public void fillShapeShadow(Shape shape, int fillColor, int fillAlpha, int shadowColor, float shadowOpacity, int blurRadius, int offsetX, int offsetY)Fills the given shape and casts a blurred drop shadow behind it in a single GPU-accelerated draw where the platform supports it (e.g. Android Paint.setShadowLayer, iOS CGContextSetShadow), with no retained bitmap.
public boolean isShapeShadowSupported()Checks whether #fillShapeShadow renders a GPU shadow on this platform.
public boolean isTransformSupported()Checks to see if com.codename1.ui.geom.Matrix transforms are supported by this graphics context.
public boolean isPerspectiveTransformSupported()Checks to see if perspective (3D) com.codename1.ui.geom.Matrix transforms are supported by this graphics context.
public boolean isShapeSupported()Checks to see if this graphics context supports drawing shapes (i.e. #drawShape and #fillShape methods. If this returns false, and you call #drawShape or #fillShape, then nothing will be drawn.
public boolean isShapeClipSupported()Checks to see if this graphics context supports clip Shape.
public void transform(Transform transform)Concatenates the given transform to the context’s transform.
public Transform getTransform()Deprecated Gets the transformation matrix that is currently applied to this graphics context.
public void setTransform(Transform transform)Sets the transformation com.codename1.ui.geom.Matrix to apply to drawing in this graphics context.
public void getTransform(Transform t)Loads the provided transform with the current transform applied to this graphics context.
public void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3)Draws a filled triangle with the given coordinates
public void fillRadialGradient(int startColor, int endColor, int x, int y, int width, int height)Draws a radial gradient in the given coordinates with the given colors, doesn’t take alpha into consideration when drawing the gradient.
public void fillRadialGradient(int startColor, int endColor, int x, int y, int width, int height, int startAngle, int arcAngle)Draws a radial gradient in the given coordinates with the given colors, doesn’t take alpha into consideration when drawing the gradient.
public void fillRectRadialGradient(int startColor, int endColor, int x, int y, int width, int height, float relativeX, float relativeY, float relativeSize)Draws a radial gradient in the given coordinates with the given colors, doesn’t take alpha into consideration when drawing the gradient.
public void fillLinearGradient(int startColor, int endColor, int x, int y, int width, int height, boolean horizontal)Draws a linear gradient in the given coordinates with the given colors, doesn’t take alpha into consideration when drawing the gradient
public void fillGradient(Gradient gradient, int x, int y, int width, int height)Fills the rectangle (x, y, width, height) with the given multi-stop gradient.
public Image gaussianBlur(Image source, float radius)Returns a copy of the given image with a Gaussian blur of the given radius applied.
public boolean blurRegion(int x, int y, int width, int height, float radius)Applies a Gaussian blur to the contents already painted into the rectangular region.
public boolean glassRegion(int x, int y, int width, int height, float radius, float cornerRadius, float sat, float scale, float offset, float refract, float specular)Applies the iOS “Liquid Glass” material to the contents already painted into the rectangular region.
public boolean lensRegion(int x, int y, int width, int height, float cornerRadius, float magnify, float aberration, int tintColor, float tintStrength)Applies the iOS 26 selection “drop” LENS to the contents already painted into the region (the bar + glyphs UNDER it): radial magnification, edge chromatic aberration, and a luminance-keyed dark->accent tint so dark glyphs read in the accent colour only where the lens covers them.
public void fillRect(int x, int y, int w, int h, byte alpha)Fills a rectangle with an optionally translucent fill color
public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)Fills a closed polygon defined by arrays of x and y coordinates.
public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)Draws a closed polygon defined by arrays of x and y coordinates.
public boolean isAlphaSupported()Indicates whether invoking set/getAlpha would have an effect on all further rendering from this graphics object.
public int setAndGetAlpha(int a)Sets alpha as a value between 0-255 (0 - 0xff) where 255 is completely opaque and 0 is completely transparent
public int concatenateAlpha(int a)Concatenates the given alpha value to the current alpha setting, and returns the previous alpha setting.
public int getAlpha()Returns the alpha as a value between 0-255 (0 - 0xff) where 255 is completely opaque and 0 is completely transparent
public void setAlpha(int a)Sets alpha as a value between 0-255 (0 - 0xff) where 255 is completely opaque and 0 is completely transparent
public boolean isAntiAliasingSupported()Returns true if antialiasing for standard rendering operations is supported, notice that text antialiasing is a separate attribute.
public boolean isAntiAliasedTextSupported()Returns true if antialiasing for text is supported, notice that text antialiasing is a separate attribute from standard anti-alisaing.
public boolean isAntiAliased()Returns true if antialiasing for standard rendering operations is turned on.
public void setAntiAliased(boolean a)Set whether antialiasing for standard rendering operations is turned on.
public boolean isAntiAliasedText()Indicates whether antialiasing for text is active, notice that text antialiasing is a separate attribute from standard anti-alisaing.
public void setAntiAliasedText(boolean a)Set whether antialiasing for text is active, notice that text antialiasing is a separate attribute from standard anti-alisaing.
public boolean isAffineSupported()Indicates whether the underlying implementation can draw using an affine transform hence methods such as rotate, scale and shear would work
public void resetAffine()Resets the affine transform to the default value
public void scale(float x, float y)Scales the coordinate system using the affine transform
public void translateMatrix(float x, float y)Translates the coordinate system using the affine transform matrix (as opposed to #translate(int, int) which uses a per-Graphics integer accumulator).
public boolean isTranslateMatrixSupported()Checks whether #translateMatrix(float, float) composes through the impl matrix on this port (the matrix-correct mode) versus falling back to the integer #translate(int, int) accumulator.
public void rotate(float angle)Deprecated Rotates the coordinate system around a radian angle using the affine transform
public void rotateRadians(float angle)RRotates the coordinate system around a radian angle using the affine transform
public void rotate(float angle, int pivotX, int pivotY)Deprecated Rotates the coordinate system around a radian angle using the affine transform
public void rotateRadians(float angle, int pivotX, int pivotY)Rotates the coordinate system around a radian angle using the affine transform
public void shear(float x, float y)Shear the graphics coordinate system using the affine transform
public Object beginNativeGraphicsAccess()Starts accessing the native graphics in the underlying OS, when accessing the native graphics Codename One shouldn’t be used! The native graphics is unclipped and untranslated by default and its the responsibility of the caller to clip/translate appropriately.
public void endNativeGraphicsAccess()Invoke this to restore Codename One’s graphics settings into the native graphics
public void tileImage(Image img, int x, int y, int w, int h)Allows an implementation to optimize image tiling rendering logic
public float getScaleX()Returns the affine X scale
public float getScaleY()Returns the affine Y scale
public int getRenderingHints()Gets the current rendering hints for this context.
public void setRenderingHints(int hints)Sets rendering hints for this context.

Inherited methods

Field details

RENDERING_HINT_FAST

public static final int RENDERING_HINT_FAST = 1
Rendering hint to indicate that the context should prefer to render primitives in a quick way, at the cost of quality, if there is an expensive operation.

Method details

finalize

protected void finalize()

translate

public void translate(int x, int y)
Translates the X/Y location for drawing on the underlying surface. Translation is incremental so the new value will be added to the current translation and in order to reset translation we have to invoke translate(-getTranslateX(), -getTranslateY())

Parameters

x int
the x coordinate
y int
the y coordinate

getTranslateX

public int getTranslateX()
Returns the current x translate value

Returns

the current x translate value

getTranslateY

public int getTranslateY()
Returns the current y translate value

Returns

the current y translate value

getColor

public int getColor()
Returns the current color

Returns

the RGB graphics color

setColor

public void setColor(int rgb)
Sets the current rgb color while ignoring any potential alpha component within said color value.

Parameters

rgb int
the RGB value for the color.

setColor

public void setColor(Paint paint)
Sets paint to be used for filling shapes. This is only used for the #fillShape(com.codename1.ui.geom.Shape) method.

getPaint

public Paint getPaint()
Gets the current Paint that is set to be used for filling shapes.

Returns

The paint that is to be used for filling shapes.

setAndGetColor

public int setAndGetColor(int rgb)
Sets the current rgb color while ignoring any potential alpha component within said color value.

Parameters

rgb int
the RGB value for the color.

Returns

The previous color value.

getFont

public Font getFont()
Returns the font used with the drawString method calls

Returns

the font used with the drawString method calls

setFont

public void setFont(Font font)
Sets the font to use with the drawString method calls

Parameters

font Font
the font used with the drawString method calls

getClipX

public int getClipX()
Returns the x clipping position

Returns

the x clipping position

getClip

public int[] getClip()
Returns the clip as an x,y,w,h array

Returns

clip array copy

setClip

public void setClip(int[] clip)
Sets the clip from an array containing x, y, width, height value

Parameters

clip int[]
4 element array

setClip

public void setClip(Shape shape)

Clips the Graphics context to the Shape.

This is not supported on all platforms and contexts currently. Use #isShapeClipSupported to check if the current context supports clipping shapes.

Image duke = null;
try {
    // duke.png is just the default Codename One icon copied into place
    duke = Image.createImage("/duke.png");
} catch(IOException err) {
    Log.e(err);
}
final Image finalDuke = duke;

Form hi = new Form("Shape Clip");

// We create a 50 x 100 shape, this is arbitrary since we can scale it easily
GeneralPath path = new GeneralPath();
path.moveTo(20,0);
path.lineTo(30, 0);
path.lineTo(30, 100);
path.lineTo(20, 100);
path.lineTo(20, 15);
path.lineTo(5, 40);
path.lineTo(5, 25);
path.lineTo(20,0);

Stroke stroke = new Stroke(0.5f, Stroke.CAP_ROUND, Stroke.JOIN_ROUND, 4);
hi.getContentPane().getUnselectedStyle().setBgPainter(new Painter() {
    public void paint(Graphics g, Rectangle rect) {
    g.setColor(0xff);
    float widthRatio = ((float)rect.getWidth()) / 50f;
    float heightRatio = ((float)rect.getHeight()) / 100f;
    g.scale(widthRatio, heightRatio);
    g.translate((int)(((float)rect.getX()) / widthRatio), (int)(((float)rect.getY()) / heightRatio));
    g.setClip(path);
    g.setAntiAliased(true);
    g.drawImage(finalDuke, 0, 0, 50, 100);
    g.setClip(path.getBounds());
    g.drawShape(path, stroke);
    g.translate(-(int)(((float)rect.getX()) / widthRatio), -(int)(((float)rect.getY()) / heightRatio));
    g.resetAffine();
    }
});

hi.show();

Parameters

shape Shape
The shape to clip.

getClipY

public int getClipY()
Returns the y clipping position

Returns

the y clipping position

getClipWidth

public int getClipWidth()
Returns the clip width

Returns

the clip width

getClipHeight

public int getClipHeight()
Returns the clip height

Returns

the clip height

isVisible

public boolean isVisible(int x, int y, int w, int h)

Returns true if the given rectangle (in the current Graphics coordinate space, with the active translation applied) intersects the current clip rectangle, i.e. anything drawn into it would be at least partially visible.

Use this to skip work for off-screen draws - typical case is a zoomed canvas where most images fall outside the visible window and should not be decoded or scaled.

if (g.isVisible(x, y, w, h)) {
    g.drawImage(image, x, y, w, h);
}

When a non-identity affine transform is in effect (see setTransform), the four corners of the rectangle are mapped through the current transform and the axis-aligned bounding box of the result is tested against the clip. This means a rotated/scaled rectangle is judged by where it actually lands on screen rather than by its untransformed coordinates. The integer translate (translate) is intentionally not added here: getClipX/getClipY are already reported in the same untranslated coordinate space you pass to draw calls, so the translation cancels out.

Note: shape-clipped graphics (setClip(Shape)) fall back to the bounding rectangle of the clip, and perspective (3D) transforms are approximated by their 2D corner projection; this matches the precision actually used by the platform draw calls.

Parameters

x int
left edge of the rectangle
y int
top edge of the rectangle
w int
width of the rectangle
h int
height of the rectangle

Returns

true if the rectangle intersects the current clip

clipRect

public void clipRect(int x, int y, int width, int height)
Clips the given rectangle by intersecting with the current clipping region, this method can thus only shrink the clipping region and never increase it.

Parameters

x int
the x coordinate of the rectangle to intersect the clip with
y int
the y coordinate of the rectangle to intersect the clip with
width int
the width of the rectangle to intersect the clip with
height int
the height of the rectangle to intersect the clip with

setClip

public void setClip(int x, int y, int width, int height)
Updates the clipping region to match the given region exactly

Parameters

x int
the x coordinate of the new clip rectangle.
y int
the y coordinate of the new clip rectangle.
width int
the width of the new clip rectangle.
height int
the height of the new clip rectangle.

pushClip

public void pushClip()
Pushes the current clip onto the clip stack. It can later be restored using #popClip.

popClip

public void popClip()
Pops the top clip from the clip stack and sets it as the current clip.

drawLine

public void drawLine(int x1, int y1, int x2, int y2)
Draws a line between the 2 X/Y coordinates

Parameters

x1 int
first x position
y1 int
first y position
x2 int
second x position
y2 int
second y position

fillRect

public void fillRect(int x, int y, int width, int height)
Fills the rectangle from the given position according to the width/height minus 1 pixel according to the convention in Java.

Parameters

x int
the x coordinate of the rectangle to be filled.
y int
the y coordinate of the rectangle to be filled.
width int
the width of the rectangle to be filled.
height int
the height of the rectangle to be filled.

drawShadow

public void drawShadow(Image img, int x, int y, int offsetX, int offsetY, int blurRadius, int spreadRadius, int color, float opacity)
Deprecated. this method should have been internals

clearRect

public void clearRect(int x, int y, int width, int height)

Clears rectangular area of the graphics context. This will remove any color information that has already been drawn to the graphics context making it transparent.

The difference between this method and say int, int, int) with alpha=0 is that fillRect() will just blend with the colors underneath (and thus int, int, int) with an alpha of 0 actually does nothing.

NOTE: In contrast to other drawing methods, coordinates input here are absolute and will not be adjusted by the xTranslate and yTranslate values

This method is designed to be used by #drawPeerComponent(com.codename1.ui.PeerComponent) only.

Parameters

x int
The x-coordinate of the box to clear. In screen coordinates.
y int
The y-coordinate of the box to clear. In screen coordinates.
width int
The width of the box to clear.
height int
The height of the box to clear.

drawRect

public void drawRect(int x, int y, int width, int height)
Draws a rectangle in the given coordinates

Parameters

x int
the x coordinate of the rectangle to be drawn.
y int
the y coordinate of the rectangle to be drawn.
width int
the width of the rectangle to be drawn.
height int
the height of the rectangle to be drawn.

drawRect

public void drawRect(int x, int y, int width, int height, int thickness)
Draws a rectangle in the given coordinates with the given thickness

Parameters

x int
the x coordinate of the rectangle to be drawn.
y int
the y coordinate of the rectangle to be drawn.
width int
the width of the rectangle to be drawn.
height int
the height of the rectangle to be drawn.
thickness int
the thickness in pixels

drawRoundRect

public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Draws a rounded corner rectangle in the given coordinates with the arcWidth/height matching the last two arguments respectively.

Parameters

x int
the x coordinate of the rectangle to be drawn.
y int
the y coordinate of the rectangle to be drawn.
width int
the width of the rectangle to be drawn.
height int
the height of the rectangle to be drawn.
arcWidth int
the horizontal diameter of the arc at the four corners.
arcHeight int
the vertical diameter of the arc at the four corners.

lighterColor

public void lighterColor(int factor)
Makes the current color slightly lighter, this is useful for many visual effects

Parameters

factor int
the degree of lightening a color per channel a number from 1 to 255

darkerColor

public void darkerColor(int factor)
Makes the current color slightly darker, this is useful for many visual effects

Parameters

factor int
the degree of lightening a color per channel a number from 1 to 255

fillRoundRect

public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Fills a rounded rectangle in the same way as drawRoundRect

Parameters

x int
the x coordinate of the rectangle to be filled.
y int
the y coordinate of the rectangle to be filled.
width int
the width of the rectangle to be filled.
height int
the height of the rectangle to be filled.
arcWidth int
the horizontal diameter of the arc at the four corners.
arcHeight int
the vertical diameter of the arc at the four corners.

fillArc

public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)

Fills a circular or elliptical arc based on the given angles and bounding box. The resulting arc begins at startAngle and extends for arcAngle degrees. Usage:

Form hi = new Form("fillArc / drawArc", new BorderLayout());
Container cmp = new Container();
cmp.setPreferredSize(new Dimension(300, 300));
Painter p = new Painter() {
    public void paint(Graphics g, Rectangle rect) {
        boolean antiAliased = g.isAntiAliased();
        g.setAntiAliased(true);
        int r = Math.min(rect.getWidth(), rect.getHeight()) / 2;
        int x = rect.getX() + rect.getWidth() / 2 - r;
        int y = rect.getY() + rect.getHeight() / 2 - r;
        g.setColor(0x4488ff);
        g.fillArc(x, y, 2 * r, 2 * r, 0, 360);
        g.setColor(0xffffff);
        g.drawArc(x, y, 2 * r - 1, 2 * r - 1, 0, 360);
        g.setAntiAliased(antiAliased);
    }
};
cmp.getAllStyles().setBgPainter(p);
hi.add(BorderLayout.CENTER, cmp);
hi.show();

Parameters

x int
the x coordinate of the upper-left corner of the arc to be filled.
y int
the y coordinate of the upper-left corner of the arc to be filled.
width int
the width of the arc to be filled, must be 1 or more.
height int
the height of the arc to be filled, must be 1 or more.
startAngle int
the beginning angle.
arcAngle int
the angular extent of the arc, relative to the start angle.

drawArc

public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Draws a circular or elliptical arc based on the given angles and bounding box

Parameters

x int
the x coordinate of the upper-left corner of the arc to be drawn.
y int
the y coordinate of the upper-left corner of the arc to be drawn.
width int
the width of the arc to be drawn.
height int
the height of the arc to be drawn.
startAngle int
the beginning angle.
arcAngle int
the angular extent of the arc, relative to the start angle.

drawString

public void drawString(String str, int x, int y, int textDecoration)
Draw a string using the current font and color in the x,y coordinates. The font is drawn from the top position and not the baseline.

Parameters

str String
the string to be drawn.
x int
the x coordinate.
y int
the y coordinate.
textDecoration int
Text decoration bitmask (See Style’s TEXT_DECORATION_* constants)

drawStringBaseline

public void drawStringBaseline(String str, int x, int y)
Draws a string using baseline coordinates.

Parameters

str String
The string to be drawn.
x int
The x-coordinate of the start of left edge of the text block.
y int
The y-coordinate of the baseline of the text.

drawStringBaseline

public void drawStringBaseline(String str, int x, int y, int textDecoration)
Draws a string using baseline coordinates.

Parameters

str String
The string to be drawn.
x int
The x-coordinate of the start of left edge of the text block.
y int
The y-coordinate of the baseline of the text.
textDecoration int
Text decoration bitmask (See Style’s TEXT_DECORATION_* constants)

drawString

public void drawString(String str, int x, int y)
Draw a string using the current font and color in the x,y coordinates. The font is drawn from the top position and not the baseline.

Parameters

str String
the string to be drawn.
x int
the x coordinate.
y int
the y coordinate.

drawChar

public void drawChar(char character, int x, int y)
Deprecated. use drawString instead, this method is inefficient
Draw the given char using the current font and color in the x,y coordinates. The font is drawn from the top position and not the baseline.

Parameters

character char
  • the character to be drawn
x int
the x coordinate of the baseline of the text
y int
the y coordinate of the baseline of the text

drawChars

public void drawChars(char[] data, int offset, int length, int x, int y)
Deprecated. use drawString instead, this method is inefficient
Draw the given char array using the current font and color in the x,y coordinates. The font is drawn from the top position and not the baseline.

Parameters

data char[]
the array of characters to be drawn
offset int
the start offset in the data
length int
the number of characters to be drawn
x int
the x coordinate of the baseline of the text
y int
the y coordinate of the baseline of the text

drawImage

public void drawImage(Image img, int x, int y)
Draws the image so its top left coordinate corresponds to x/y

Parameters

img Image
the specified image to be drawn. This method does nothing if img is null.
x int
the x coordinate.
y int
the y coordinate.

isRoundedImageSupported

public boolean isRoundedImageSupported()
Draws the image so its top left coordinate corresponds to x/y and scales it to width/height

isRoundedImageSupported

public boolean isRoundedImageSupported(Image img)

Whether drawImageRounded(Image, int, int, int, int, float) will round THIS image, which is the question a caller actually needs answered.

The platform may round and still not be able to round a given picture. Drawing an Image is a virtual call, and ComponentImage, DynamicImage, FontImage, RGBImage and SVGScaledView paint procedurally rather than handing over a bitmap; a rotated image keeps its angle beside a shared peer. None of those can be handed to a rounded draw without losing the drawing or the rotation, so they come out square.

A caller that consults the no-argument method alone therefore skips its own rounded-copy fallback on a platform that advertises support and gets square artwork for exactly those images. Ask this one per picture.

Parameters

img Image
the image about to be drawn

Returns

true if this image will be rounded; false to use the copy fallback

drawImageRounded

public void drawImageRounded(Image img, int x, int y, int w, int h, float cornerRadius)

Draws an image with rounded corners, without building a rounded copy of it, on platforms that support it; elsewhere the image is drawn square.

The corners are anti-aliased where the platform draws them analytically, which a shaped clip of the same outline is not.

Parameters

img Image
the image to draw
x int
destination x
y int
destination y
w int
destination width
h int
destination height
cornerRadius float
radius in pixels, clamped to half the smaller side

drawImage

public void drawImage(Image img, int x, int y, int w, int h)

drawShape

public void drawShape(Shape shape, Stroke stroke)

Draws a outline shape inside the specified bounding box. The bounding box will resize the shape to fit in its dimensions.

This is not supported on all platforms and contexts currently. Use #isShapeSupported to check if the current context supports drawing shapes.

Form hi = new Form("Shape");

// We create a 50 x 100 shape, this is arbitrary since we can scale it easily
GeneralPath path = new GeneralPath();
path.moveTo(20,0);
path.lineTo(30, 0);
path.lineTo(30, 100);
path.lineTo(20, 100);
path.lineTo(20, 15);
path.lineTo(5, 40);
path.lineTo(5, 25);
path.lineTo(20,0);

hi.getContentPane().getUnselectedStyle().setBgPainter(new Painter() {
    public void paint(Graphics g, Rectangle rect) {
    g.setColor(0xff);
    float widthRatio = ((float)rect.getWidth()) / 50f;
    float heightRatio = ((float)rect.getHeight()) / 100f;
    g.scale(widthRatio, heightRatio);
    g.translate((int)(((float)rect.getX()) / widthRatio), (int)(((float)rect.getY()) / heightRatio));
    g.fillShape(path);
    g.resetAffine();
    }
});

hi.show();

Parameters

shape Shape
The shape to be drawn.
stroke Stroke
the stroke to use

See also

fillShape

public void fillShape(Shape shape)

Fills the given shape using the current alpha and color settings.

This is not supported on all platforms and contexts currently. Use #isShapeSupported to check if the current context supports drawing shapes.

Form hi = new Form("Shape");

// We create a 50 x 100 shape, this is arbitrary since we can scale it easily
GeneralPath path = new GeneralPath();
path.moveTo(20,0);
path.lineTo(30, 0);
path.lineTo(30, 100);
path.lineTo(20, 100);
path.lineTo(20, 15);
path.lineTo(5, 40);
path.lineTo(5, 25);
path.lineTo(20,0);

hi.getContentPane().getUnselectedStyle().setBgPainter(new Painter() {
    public void paint(Graphics g, Rectangle rect) {
    g.setColor(0xff);
    float widthRatio = ((float)rect.getWidth()) / 50f;
    float heightRatio = ((float)rect.getHeight()) / 100f;
    g.scale(widthRatio, heightRatio);
    g.translate((int)(((float)rect.getX()) / widthRatio), (int)(((float)rect.getY()) / heightRatio));
    g.fillShape(path);
    g.resetAffine();
    }
});

hi.show();

Note: You can specify a custom Paint to use for filling the shape using the #setColor(com.codename1.ui.Paint) method. This is useful for filling the shape with a LinearGradientPaint, for example.

Parameters

shape Shape
The shape to be filled.

fillShapeShadow

public void fillShapeShadow(Shape shape, int fillColor, int fillAlpha, int shadowColor, float shadowOpacity, int blurRadius, int offsetX, int offsetY)
Fills the given shape and casts a blurred drop shadow behind it in a single GPU-accelerated draw where the platform supports it (e.g. Android Paint.setShadowLayer, iOS CGContextSetShadow), with no retained bitmap. This lets borders/decorations render soft shadows every frame without caching a per-component image. Guard with #isShapeShadowSupported() and fall back to your own path otherwise.

Parameters

shape Shape
the shape to fill (and whose fill casts the shadow)
fillColor int
the fill color as 0xRRGGBB
fillAlpha int
the fill alpha 0..255
shadowColor int
the shadow color as 0xRRGGBB
shadowOpacity float
the shadow opacity in the range 0..1
blurRadius int
the gaussian blur radius in pixels
offsetX int
the shadow x offset in pixels
offsetY int
the shadow y offset in pixels

isShapeShadowSupported

public boolean isShapeShadowSupported()
Checks whether #fillShapeShadow renders a GPU shadow on this platform. When false the caller should draw its shadow another way (e.g. the cached-image fallback in RoundRectBorder).

Returns

true if a GPU shape shadow is supported by the current graphics context

isTransformSupported

public boolean isTransformSupported()
Checks to see if com.codename1.ui.geom.Matrix transforms are supported by this graphics context.

Returns

true if this graphics context supports com.codename1.ui.geom.Matrix transforms.

Note that this method only confirms that 2D transforms are supported. If you need to perform 3D transformations, you should use the #isPerspectiveTransformSupported method.

isPerspectiveTransformSupported

public boolean isPerspectiveTransformSupported()

Checks to see if perspective (3D) com.codename1.ui.geom.Matrix transforms are supported by this graphics context. If 3D transforms are supported, you can use a 4x4 transformation com.codename1.ui.geom.Matrix via #setTransform to perform 3D transforms.

Note: It is possible for 3D transforms to not be supported but Affine (2D) transforms to be supported. In this case you would be limited to a 3x3 transformation matrix in #setTransform. You can check for 2D transformation support using the #isTransformSupported method.

Returns

true if Perspective (3D) transforms are supported. false otherwise.

isShapeSupported

public boolean isShapeSupported()
Checks to see if this graphics context supports drawing shapes (i.e. #drawShape and #fillShape methods. If this returns false, and you call #drawShape or #fillShape, then nothing will be drawn.

Returns

true If #drawShape and #fillShape are supported.

isShapeClipSupported

public boolean isShapeClipSupported()
Checks to see if this graphics context supports clip Shape. If this returns false, calling setClip(Shape) will have no effect on the Graphics clipping area

Returns

true If setClip(Shape) is supported.

transform

public void transform(Transform transform)
Concatenates the given transform to the context’s transform.

Parameters

transform Transform
The transform to concatenate.

getTransform

public Transform getTransform()
Deprecated. Use #getTransform(com.codename1.ui.Transform) instead.

Gets the transformation matrix that is currently applied to this graphics context.

Unlike java.awt.Graphics2D.getTransform(), the matrix returned here does not include the integer translation set via #translate(int, int). Codename One keeps that translation as a separate accumulator (#getTranslateX() / #getTranslateY()) that is applied independently of the affine matrix, so a freshly-translated context still reports the identity transform. This split is deliberate: #setTransform / getTransform / #transform(com.codename1.ui.Transform) round-trip correctly only because the translate is excluded here – folding it in would cause it to be counted twice (once in the matrix, once in the drawing pipeline).

Consequently, to map a point from the current drawing coordinate space to the context’s device coordinates you must add the translation yourself:

float[] pt = { x + g.getTranslateX(), y + g.getTranslateY() };
g.getTransform().transformPoint(pt, pt);
// pt now holds the transformed device coordinates

If you only need to know whether a rectangle would be drawn on screen, prefer #isVisible(int, int, int, int), which performs this mapping (translate + transform) internally and tests it against the clip.

Returns

The current transformation matrix, excluding the integer translate.

setTransform

public void setTransform(Transform transform)

Sets the transformation com.codename1.ui.geom.Matrix to apply to drawing in this graphics context. In order to use this for 2D/Affine transformations you should first check to make sure that transforms are supported by calling the #isTransformSupported method. For 3D/Perspective transformations, you should first check to make sure that 3D/Perspective transformations are supported by calling the #isPerspectiveTransformSupported.

Transformations are applied with (0,0) as the origin. So rotations and scales are anchored at this point on the screen. You can use a different anchor point by either embedding it in the transformation matrix (i.e. pre-transform the com.codename1.ui.geom.Matrix to anchor at a different point) or use the int, int) variation that allows you to explicitly set the anchor point.

Parameters

transform Transform
The transformation com.codename1.ui.geom.Matrix to use for drawing. 2D/Affine transformations can be achieved using a 3x3 transformation com.codename1.ui.geom.Matrix. 3D/Perspective transformations can be achieved using a 4x3 transformation com.codename1.ui.geom.Matrix.

See also

getTransform

public void getTransform(Transform t)

Loads the provided transform with the current transform applied to this graphics context.

As with #getTransform(), the loaded matrix does not include the integer translation set via #translate(int, int); add #getTranslateX() / #getTranslateY() to a point before transforming it if you need device coordinates.

Parameters

t Transform
An “out” parameter to be filled with the current transform.

fillTriangle

public void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3)
Draws a filled triangle with the given coordinates

Parameters

x1 int
the x coordinate of the first vertex of the triangle
y1 int
the y coordinate of the first vertex of the triangle
x2 int
the x coordinate of the second vertex of the triangle
y2 int
the y coordinate of the second vertex of the triangle
x3 int
the x coordinate of the third vertex of the triangle
y3 int
the y coordinate of the third vertex of the triangle

fillRadialGradient

public void fillRadialGradient(int startColor, int endColor, int x, int y, int width, int height)
Draws a radial gradient in the given coordinates with the given colors, doesn’t take alpha into consideration when drawing the gradient. Notice that a radial gradient will result in a circular shape, to create a square use fillRect or draw a larger shape and clip to the appropriate size.

Parameters

startColor int
the starting RGB color
endColor int
the ending RGB color
x int
the x coordinate
y int
the y coordinate
width int
the width of the region to be filled
height int
the height of the region to be filled

fillRadialGradient

public void fillRadialGradient(int startColor, int endColor, int x, int y, int width, int height, int startAngle, int arcAngle)
Draws a radial gradient in the given coordinates with the given colors, doesn’t take alpha into consideration when drawing the gradient. Notice that a radial gradient will result in a circular shape, to create a square use fillRect or draw a larger shape and clip to the appropriate size.

Parameters

startColor int
the starting RGB color
endColor int
the ending RGB color
x int
the x coordinate
y int
the y coordinate
width int
the width of the region to be filled
height int
the height of the region to be filled
startAngle int
the beginning angle. Zero is at 3 o’clock. Positive angles are counter-clockwise.
arcAngle int
the angular extent of the arc, relative to the start angle. Positive angles are counter-clockwise.

fillRectRadialGradient

public void fillRectRadialGradient(int startColor, int endColor, int x, int y, int width, int height, float relativeX, float relativeY, float relativeSize)
Draws a radial gradient in the given coordinates with the given colors, doesn’t take alpha into consideration when drawing the gradient. Notice that this method differs from fillRadialGradient since it draws a square gradient at all times and can thus be cached Notice that a radial gradient will result in a circular shape, to create a square use fillRect or draw a larger shape and clip to the appropriate size.

Parameters

startColor int
the starting RGB color
endColor int
the ending RGB color
x int
the x coordinate
y int
the y coordinate
width int
the width of the region to be filled
height int
the height of the region to be filled
relativeX float
indicates the relative position of the gradient within the drawing region
relativeY float
indicates the relative position of the gradient within the drawing region
relativeSize float
indicates the relative size of the gradient within the drawing region

fillLinearGradient

public void fillLinearGradient(int startColor, int endColor, int x, int y, int width, int height, boolean horizontal)
Draws a linear gradient in the given coordinates with the given colors, doesn’t take alpha into consideration when drawing the gradient

Parameters

startColor int
the starting RGB color
endColor int
the ending RGB color
x int
the x coordinate
y int
the y coordinate
width int
the width of the region to be filled
height int
the height of the region to be filled
horizontal boolean
indicating wheter it is a horizontal fill or vertical

fillGradient

public void fillGradient(Gradient gradient, int x, int y, int width, int height)
Fills the rectangle (x, y, width, height) with the given multi-stop gradient. The Gradient may be a LinearGradient, RadialGradient, or ConicGradient - the port picks the right native shader path (Java2D LinearGradientPaint/RadialGradientPaint on JavaSE; Android LinearGradient/RadialGradient/SweepGradient shaders; software rasterizer fallback elsewhere). Pass null or width/height <= 0 for a no-op.

gaussianBlur

public Image gaussianBlur(Image source, float radius)
Returns a copy of the given image with a Gaussian blur of the given radius applied. Equivalent to the CSS filter:blur() effect on an image.

blurRegion

public boolean blurRegion(int x, int y, int width, int height, float radius)
Applies a Gaussian blur to the contents already painted into the rectangular region. Used to realize CSS backdrop-filter:blur(). Returns true if the port supports an in-place blur; otherwise the caller should fall back to snapshot + gaussianBlur().

glassRegion

public boolean glassRegion(int x, int y, int width, int height, float radius, float cornerRadius, float sat, float scale, float offset, float refract, float specular)
Applies the iOS “Liquid Glass” material to the contents already painted into the rectangular region. This is a blur followed by an affine colour transform (saturation boost + scale + offset). The material is masked to a rounded rectangle of the given corner radius (in pixels; a negative value means a full capsule/pill) so it matches the host component’s shape rather than spilling into a square. Used to realize the frosted glass backdrop-filter material.

lensRegion

public boolean lensRegion(int x, int y, int width, int height, float cornerRadius, float magnify, float aberration, int tintColor, float tintStrength)
Applies the iOS 26 selection “drop” LENS to the contents already painted into the region (the bar + glyphs UNDER it): radial magnification, edge chromatic aberration, and a luminance-keyed dark->accent tint so dark glyphs read in the accent colour only where the lens covers them. Unlike glassRegion this is drawn OVER the content. cornerRadius<0 = capsule. tintColor is 0xRRGGBB.

fillRect

public void fillRect(int x, int y, int w, int h, byte alpha)
Fills a rectangle with an optionally translucent fill color

Parameters

x int
the x coordinate of the rectangle to be filled
y int
the y coordinate of the rectangle to be filled
w int
the width of the rectangle to be filled
h int
the height of the rectangle to be filled
alpha byte
the alpha values specify semitransparency

fillPolygon

public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
Fills a closed polygon defined by arrays of x and y coordinates. Each pair of (x, y) coordinates defines a point.

Parameters

xPoints int[]
  • a an array of x coordinates.
yPoints int[]
  • a an array of y coordinates.
nPoints int
  • a the total number of points.

drawPolygon

public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
Draws a closed polygon defined by arrays of x and y coordinates. Each pair of (x, y) coordinates defines a point.

Parameters

xPoints int[]
  • an array of x coordinates.
yPoints int[]
  • an array of y coordinates.
nPoints int
  • the total number of points.

isAlphaSupported

public boolean isAlphaSupported()
Indicates whether invoking set/getAlpha would have an effect on all further rendering from this graphics object.

Returns

false if setAlpha has no effect true if it applies to everything some effect

setAndGetAlpha

public int setAndGetAlpha(int a)
Sets alpha as a value between 0-255 (0 - 0xff) where 255 is completely opaque and 0 is completely transparent

Parameters

a int
the alpha value

Returns

The previous alpha value.

concatenateAlpha

public int concatenateAlpha(int a)
Concatenates the given alpha value to the current alpha setting, and returns the previous alpha setting.

Parameters

a int
Alpha value to concatenate (0-255).

Returns

The previous alpha setting (0-255).

getAlpha

public int getAlpha()
Returns the alpha as a value between 0-255 (0 - 0xff) where 255 is completely opaque and 0 is completely transparent

Returns

the alpha value

setAlpha

public void setAlpha(int a)
Sets alpha as a value between 0-255 (0 - 0xff) where 255 is completely opaque and 0 is completely transparent

Parameters

a int
the alpha value

isAntiAliasingSupported

public boolean isAntiAliasingSupported()
Returns true if antialiasing for standard rendering operations is supported, notice that text antialiasing is a separate attribute.

Returns

true if antialiasing is supported

isAntiAliasedTextSupported

public boolean isAntiAliasedTextSupported()
Returns true if antialiasing for text is supported, notice that text antialiasing is a separate attribute from standard anti-alisaing.

Returns

true if text antialiasing is supported

isAntiAliased

public boolean isAntiAliased()
Returns true if antialiasing for standard rendering operations is turned on.

Returns

true if antialiasing is active

setAntiAliased

public void setAntiAliased(boolean a)
Set whether antialiasing for standard rendering operations is turned on.

Parameters

a boolean
true if antialiasing is active

isAntiAliasedText

public boolean isAntiAliasedText()
Indicates whether antialiasing for text is active, notice that text antialiasing is a separate attribute from standard anti-alisaing.

Returns

true if text antialiasing is supported

setAntiAliasedText

public void setAntiAliasedText(boolean a)
Set whether antialiasing for text is active, notice that text antialiasing is a separate attribute from standard anti-alisaing.

Parameters

a boolean
true if text antialiasing is supported

isAffineSupported

public boolean isAffineSupported()
Indicates whether the underlying implementation can draw using an affine transform hence methods such as rotate, scale and shear would work

Returns

true if an affine transformation matrix is present

resetAffine

public void resetAffine()
Resets the affine transform to the default value

scale

public void scale(float x, float y)
Scales the coordinate system using the affine transform

Parameters

x float
scale factor for x
y float
scale factor for y

translateMatrix

public void translateMatrix(float x, float y)

Translates the coordinate system using the affine transform matrix (as opposed to #translate(int, int) which uses a per-Graphics integer accumulator). On every port today isTranslationSupported() == false, which means g.translate(int, int) is added to draw coordinates before the impl matrix is applied; a subsequent g.scale() or g.rotate() therefore multiplies the integer translate too. That’s surprising when porting code that came from Java2D / AWT where translate composes into the matrix the same way as scale and rotate.

translateMatrix composes the translation directly onto the impl matrix, exactly like #scale(float, float) and #rotate(float) do. The result is uniform “post-multiply translate onto the current transform” semantics across iOS / JavaSE / Android / JavaScript – the same code produces the same on-screen position regardless of which port you target or whether you’re drawing into a Form’s Graphics or a mutable Image’s Graphics.

On ports where #isTranslateMatrixSupported() returns false (e.g. the legacy JavaScript port) the call falls back to the integer #translate(int, int) so apps don’t silently render at the wrong position – the visual result on those ports matches whatever translate(int, int) does there.

Parameters

x float
x-axis translation
y float
y-axis translation

isTranslateMatrixSupported

public boolean isTranslateMatrixSupported()
Checks whether #translateMatrix(float, float) composes through the impl matrix on this port (the matrix-correct mode) versus falling back to the integer #translate(int, int) accumulator. Use this to gate code that needs matrix-correct translation semantics.

Returns

true if translateMatrix reaches the impl matrix; false on ports where it falls back to the integer accumulator.

rotate

public void rotate(float angle)
Deprecated. The behaviour of this method is inconsistent with the rest of the API, in that it doesn’t take into account the current Graphics context’s translation. Rotation is performed around the Screen’s origin rather than the current Graphics context’s translated origin. Prefer to use #rotateRadians(float) which pivots around the context’s translated origin.
Rotates the coordinate system around a radian angle using the affine transform

Parameters

angle float
the rotation angle in radians about the screen origin.

rotateRadians

public void rotateRadians(float angle)
RRotates the coordinate system around a radian angle using the affine transform

Parameters

angle float
the rotation angle in radians about graphics context’s translated origin.

rotate

public void rotate(float angle, int pivotX, int pivotY)
Deprecated. The behaviour of this method is inconsistent with the rest of the API, in that the pivotX and pivotY parameters are expressed in absolute screen coordinates and don’t take into account the current Graphics context’s translation. Prefer to use int, int) whose pivot coordinates are relative to the current translation.
Rotates the coordinate system around a radian angle using the affine transform

Parameters

angle float
the rotation angle in radians
pivotX int
the pivot point In absolute coordinates.
pivotY int
the pivot point In absolute coordinates.

rotateRadians

public void rotateRadians(float angle, int pivotX, int pivotY)
Rotates the coordinate system around a radian angle using the affine transform

Parameters

angle float
the rotation angle in radians
pivotX int
the pivot point relative to the current graphics context’s translation.
pivotY int
the pivot point relative to the current graphics context’s translation.

shear

public void shear(float x, float y)
Shear the graphics coordinate system using the affine transform

Parameters

x float
shear factor for x
y float
shear factor for y

beginNativeGraphicsAccess

public Object beginNativeGraphicsAccess()

Starts accessing the native graphics in the underlying OS, when accessing the native graphics Codename One shouldn’t be used! The native graphics is unclipped and untranslated by default and its the responsibility of the caller to clip/translate appropriately.

When finished with the native graphics it is essential to invoke endNativeGraphicsAccess

Returns

an instance of the underlying native graphics object

endNativeGraphicsAccess

public void endNativeGraphicsAccess()
Invoke this to restore Codename One’s graphics settings into the native graphics

tileImage

public void tileImage(Image img, int x, int y, int w, int h)
Allows an implementation to optimize image tiling rendering logic

Parameters

img Image
the image
x int
coordinate to tile the image along
y int
coordinate to tile the image along
w int
coordinate to tile the image along
h int
coordinate to tile the image along

getScaleX

public float getScaleX()
Returns the affine X scale

Returns

the current scale

getScaleY

public float getScaleY()
Returns the affine Y scale

Returns

the current scale

getRenderingHints

public int getRenderingHints()
Gets the current rendering hints for this context.

Returns

The rendering hints.

setRenderingHints

public void setRenderingHints(int hints)
Sets rendering hints for this context.

Parameters

hints int
int of rendering hints produced by logical AND on all applicable hints.