- java.awt.Color использование в Android
- 2 ответа
- Похожие вопросы:
- Java AWT | Цветовой класс
- Android java awt color
- Constructor Summary
- Method Summary
- Methods inherited from class java.lang.Object
- Constructor Detail
- Graphics
- Method Detail
- create
- create
- translate
- getColor
- setColor
- setPaintMode
- setXORMode
- getFont
- setFont
- getFontMetrics
- getFontMetrics
- getClipBounds
- clipRect
- setClip
- getClip
- setClip
- copyArea
- drawLine
- fillRect
- drawRect
- clearRect
- drawRoundRect
- fillRoundRect
- draw3DRect
- fill3DRect
- drawOval
- fillOval
- drawArc
- fillArc
- drawPolyline
- drawPolygon
- drawPolygon
- fillPolygon
- fillPolygon
- drawString
- drawString
- drawChars
- drawBytes
- drawImage
- drawImage
- drawImage
- drawImage
- drawImage
- drawImage
- dispose
- finalize
- toString
- getClipRect
- hitClip
- getClipBounds
java.awt.Color использование в Android
Для моего приложения android мне нужно разработать конвертер текста в PDF, и я использовал для него XSPDF ( http://code.google.com/p/xspdf/). Здесь для установки цвета шрифта я не могу использовать android.graphics.Color, потому что метод требовал java.awt.Color в качестве параметра.
Я добавил системную библиотеку JRE в путь сборки Java. но я получил фатальное исключение:
Кто-нибудь знает решение этой проблемы?
2 ответа
Я пишу графическую библиотеку в Java. Это будет фронт-энд для нескольких существующих графических пакетов Java, объединяющий функции из java.awt и javax.swing. Я учитель и создаю эту библиотеку для своих начинающих учеников, чтобы им не приходилось возиться с мешаниной импортных утверждений. Я.
Это мой первый проект Swing на Eclipse, и я не могу установить цвет фона компонента. Я уже пробовал использовать этот код : B_Send.setBackground(new java.awt.color(0,0,255)); который возвращает ошибку: java.awt.color не может быть разрешен в тип Может ли кто-нибудь объяснить ошибку и почему код не.
Весь java.awt.* не является частью Android. Вы не можете использовать эту библиотеку напрямую. Android использует совершенно другую технологию для создания UI элементов.
Вы можете получить необходимый код из мертвого проекта Harmony, затем изменить имя пакета и рефракторировать проект, который вы переносите.
Это решение предполагает, что вы переносите и перекомпилируете проект, для которого требуются классы awt.
Похожие вопросы:
Я заметил, что JavaFX определяет свой собственный цветовой класс, который внешне очень похож на старый класс java.awt.Color. Они оба представляют RGB цветов с Альфа-значениями. В чем разница между.
У меня есть эта простая страница Jsp: Который завершается со следующей ошибкой.
Я хотел бы преобразовать объект java.awt.color в строку. Color c = new Color(255,0,0); System.out.print(Color.toString); Он печатает java.awt.Color[r=255, g=0, b=0] Теперь я предполагаю разобрать.
Я пишу графическую библиотеку в Java. Это будет фронт-энд для нескольких существующих графических пакетов Java, объединяющий функции из java.awt и javax.swing. Я учитель и создаю эту библиотеку для.
Это мой первый проект Swing на Eclipse, и я не могу установить цвет фона компонента. Я уже пробовал использовать этот код : B_Send.setBackground(new java.awt.color(0,0,255)); который возвращает.
я хочу сериализовать и десериализовать объект, содержащий цветовой массив. (color[][]) Цветовой массив представляет собой небольшой значок. После некоторых сборок я получаю ошибку, когда пытаюсь.
Источник
Java AWT | Цветовой класс
Класс Color является частью пакета Java Abstract Window Toolkit (AWT). Класс Color создает цвет, используя заданные значения RGBA , где RGBA означает RED, зеленый, синий, ALPHA или с использованием значения HSB HSB , где обозначает оттенок, насыщенность, BRIcomponents. Значение для отдельных компонентов RGBA колеблется от 0 до 255 или от 0,0 до 0,1. Значение альфа определяет непрозрачность цвета, где 0 или 0.0 означает полностью прозрачный, а 255 или 1.0 означает непрозрачный.
Конструкторы класса Color
- Color (ColorSpace c, float [] co, float a) : создает цвет в указанном ColorSpace с компонентами цвета, указанными в массиве float и указанной альфа.
- Цвет (float r, float g, float b) : создает непрозрачный цвет с указанными компонентами RGB (значения находятся в диапазоне 0.0 — 0.1)
- Цвет (float r, float g, float b, float a) : создает цвет с указанными компонентами RGBA (значения находятся в диапазоне 0,0 — 0,1)
- Цвет (int rgb) : создает непрозрачный цвет RGB с указанным комбинированным значением RGB, состоящим из красного компонента в битах 16-23, зеленого компонента в битах 8–15 и синего компонента в битах 0–7.
- Color (int rgba, boolean b) : создает цвет sRGB с указанным комбинированным значением RGBA, состоящим из альфа-компонента в битах 24–31, красного компонента в битах 16–23, зеленого компонента в битах 8
— 15, а синий компонент в битах 0 — 7. - Цвет (int r, int g, int b) : создает непрозрачный цвет с указанными компонентами RGB (значения находятся в диапазоне 0 — 255)
- Цвет (int r, int g, int b, int a) : создает цвет с указанными компонентами RGBA (значения находятся в диапазоне 0 — 255)
Обычно используемые методы в цветном классе
method | explanation |
---|---|
brighter() | creates a new Color that is a brighter version of this Color. |
createContext(ColorModel cm, Rectangle r, Rectangle2D r2d, AffineTransform x, RenderingHints h) | creates and returns a PaintContext used to generate a solid color field pattern. |
darker() /td> | creates a new Color that is a darker version of this Color. |
decode(String nm) | converts a String to an integer and returns the specified opaque Color. |
equals(Object obj) | determines whether another Color object is equal to this Color. |
getAlpha() | returns the alpha component in the range 0-255. |
getBlue() | returns the blue component in the range 0-255 . |
getColor(String nm) | Finds a color in the system properties. |
getColor(String nm, Color v) | Finds a color in the system properties. |
getColor(String nm, int v) | Finds a color in the system properties. |
getColorComponents(ColorSpace cspace, float[] compArray) | returns a float array containing only the color components of the Color in the ColorSpace specified by the cspace parameter. |
getColorComponents(float[] compArray) | returns a float array containing only the color components of the Color, in the ColorSpace of the Color. |
getColorSpace() | returns the ColorSpace of this Color. |
getGreen() | returns the green component in the range 0-255 in the default sRGB space. |
getRed() | returns the red component in the range 0-255 in the default sRGB space. |
getRGB() | Returns the RGB value representing the color in the default sRGB ColorModel. |
getHSBColor(float h, float s, float b) | Creates a Color object based on the specified values for the HSB color model. |
getTransparency() | returns the transparency mode for this Color. |
hashCode() | computes the hash code for this Color. |
HSBtoRGB(float h, float s, float b) | Converts the HSB value to RGB value |
RGBtoHSB(int r, int g, int b, float[] hsbvals) | converts the RGB value to HSB value |
Ниже программы иллюстрируют класс Color в Java AWT:
- Программа для установки цвета фона панели с использованием цвета, указанного в константах класса
// Java программа для установки цвета фона панели
// используя цвет, указанный в константах
// класса.
Источник
Android java awt color
A Graphics object encapsulates state information needed for the basic rendering operations that Java supports. This state information includes the following properties:
- The Component object on which to draw.
- A translation origin for rendering and clipping coordinates.
- The current clip.
- The current color.
- The current font.
- The current logical pixel operation function (XOR or Paint).
- The current XOR alternation color (see setXORMode(java.awt.Color) ).
Coordinates are infinitely thin and lie between the pixels of the output device. Operations that draw the outline of a figure operate by traversing an infinitely thin path between pixels with a pixel-sized pen that hangs down and to the right of the anchor point on the path. Operations that fill a figure operate by filling the interior of that infinitely thin path. Operations that render horizontal text render the ascending portion of character glyphs entirely above the baseline coordinate.
The graphics pen hangs down and to the right from the path it traverses. This has the following implications:
- If you draw a figure that covers a given rectangle, that figure occupies one extra row of pixels on the right and bottom edges as compared to filling a figure that is bounded by that same rectangle.
- If you draw a horizontal line along the same y coordinate as the baseline of a line of text, that line is drawn entirely below the text, except for any descenders.
All coordinates that appear as arguments to the methods of this Graphics object are considered relative to the translation origin of this Graphics object prior to the invocation of the method.
All rendering operations modify only pixels which lie within the area bounded by the current clip, which is specified by a Shape in user space and is controlled by the program using the Graphics object. This user clip is transformed into device space and combined with the device clip, which is defined by the visibility of windows and device extents. The combination of the user clip and device clip defines the composite clip, which determines the final clipping region. The user clip cannot be modified by the rendering system to reflect the resulting composite clip. The user clip can only be changed through the setClip or clipRect methods. All drawing or writing is done in the current color, using the current paint mode, and in the current font.
Constructor Summary
Modifier | Constructor and Description |
---|---|
protected | Graphics () |
Method Summary
Modifier and Type | Method and Description |
---|---|
abstract void | clearRect (int x, int y, int width, int height) |
Methods inherited from class java.lang.Object
Constructor Detail
Graphics
Since Graphics is an abstract class, applications cannot call this constructor directly. Graphics contexts are obtained from other graphics contexts or are created by calling getGraphics on a component.
Method Detail
create
create
translate
getColor
setColor
setPaintMode
setXORMode
When drawing operations are performed, pixels which are the current color are changed to the specified color, and vice versa.
Pixels that are of colors other than those two colors are changed in an unpredictable but reversible manner; if the same figure is drawn twice, then all pixels are restored to their original values.
getFont
setFont
getFontMetrics
getFontMetrics
getClipBounds
clipRect
setClip
getClip
setClip
copyArea
drawLine
fillRect
drawRect
clearRect
Beginning with Java 1.1, the background color of offscreen images may be system dependent. Applications should use setColor followed by fillRect to ensure that an offscreen image is cleared to a specific color.
drawRoundRect
fillRoundRect
draw3DRect
The colors used for the highlighting effect are determined based on the current color. The resulting rectangle covers an area that is width + 1 pixels wide by height + 1 pixels tall.
fill3DRect
drawOval
The oval covers an area that is width + 1 pixels wide and height + 1 pixels tall.
fillOval
drawArc
The resulting arc begins at startAngle and extends for arcAngle degrees, using the current color. Angles are interpreted such that 0 degrees is at the 3 o’clock position. A positive value indicates a counter-clockwise rotation while a negative value indicates a clockwise rotation.
The center of the arc is the center of the rectangle whose origin is (x, y) and whose size is specified by the width and height arguments.
The resulting arc covers an area width + 1 pixels wide by height + 1 pixels tall.
The angles are specified relative to the non-square extents of the bounding rectangle such that 45 degrees always falls on the line from the center of the ellipse to the upper right corner of the bounding rectangle. As a result, if the bounding rectangle is noticeably longer in one axis than the other, the angles to the start and end of the arc segment will be skewed farther along the longer axis of the bounds.
fillArc
The resulting arc begins at startAngle and extends for arcAngle degrees. Angles are interpreted such that 0 degrees is at the 3 o’clock position. A positive value indicates a counter-clockwise rotation while a negative value indicates a clockwise rotation.
The center of the arc is the center of the rectangle whose origin is (x, y) and whose size is specified by the width and height arguments.
The resulting arc covers an area width + 1 pixels wide by height + 1 pixels tall.
The angles are specified relative to the non-square extents of the bounding rectangle such that 45 degrees always falls on the line from the center of the ellipse to the upper right corner of the bounding rectangle. As a result, if the bounding rectangle is noticeably longer in one axis than the other, the angles to the start and end of the arc segment will be skewed farther along the longer axis of the bounds.
drawPolyline
drawPolygon
This method draws the polygon defined by nPoint line segments, where the first nPoint — 1 line segments are line segments from (xPoints[i — 1], yPoints[i — 1]) to (xPoints[i], yPoints[i]) , for 1 ≤ i ≤ nPoints . The figure is automatically closed by drawing a line connecting the final point to the first point, if those points are different.
drawPolygon
fillPolygon
This method draws the polygon defined by nPoint line segments, where the first nPoint — 1 line segments are line segments from (xPoints[i — 1], yPoints[i — 1]) to (xPoints[i], yPoints[i]) , for 1 ≤ i ≤ nPoints . The figure is automatically closed by drawing a line connecting the final point to the first point, if those points are different.
The area inside the polygon is defined using an even-odd fill rule, also known as the alternating rule.
fillPolygon
The area inside the polygon is defined using an even-odd fill rule, also known as the alternating rule.
drawString
drawString
The baseline of the leftmost character is at position (x, y) in this graphics context’s coordinate system.
drawChars
drawBytes
Use of this method is not recommended as each byte is interpreted as a Unicode code point in the range 0 to 255, and so can only be used to draw Latin characters in that range.
drawImage
This method returns immediately in all cases, even if the complete image has not yet been loaded, and it has not been dithered and converted for the current output device.
If the image has completely loaded and its pixels are no longer being changed, then drawImage returns true . Otherwise, drawImage returns false and as more of the image becomes available or it is time to draw another frame of animation, the process that loads the image notifies the specified image observer.
drawImage
The image is drawn inside the specified rectangle of this graphics context’s coordinate space, and is scaled if necessary. Transparent pixels do not affect whatever pixels are already there.
This method returns immediately in all cases, even if the entire image has not yet been scaled, dithered, and converted for the current output device. If the current output representation is not yet complete, then drawImage returns false . As more of the image becomes available, the process that loads the image notifies the image observer by calling its imageUpdate method.
A scaled version of an image will not necessarily be available immediately just because an unscaled version of the image has been constructed for this output device. Each size of the image may be cached separately and generated from the original data in a separate image production sequence.
drawImage
This operation is equivalent to filling a rectangle of the width and height of the specified image with the given color and then drawing the image on top of it, but possibly more efficient.
This method returns immediately in all cases, even if the complete image has not yet been loaded, and it has not been dithered and converted for the current output device.
If the image has completely loaded and its pixels are no longer being changed, then drawImage returns true . Otherwise, drawImage returns false and as more of the image becomes available or it is time to draw another frame of animation, the process that loads the image notifies the specified image observer.
drawImage
The image is drawn inside the specified rectangle of this graphics context’s coordinate space, and is scaled if necessary. Transparent pixels are drawn in the specified background color. This operation is equivalent to filling a rectangle of the width and height of the specified image with the given color and then drawing the image on top of it, but possibly more efficient.
This method returns immediately in all cases, even if the entire image has not yet been scaled, dithered, and converted for the current output device. If the current output representation is not yet complete then drawImage returns false . As more of the image becomes available, the process that loads the image notifies the specified image observer.
A scaled version of an image will not necessarily be available immediately just because an unscaled version of the image has been constructed for this output device. Each size of the image may be cached separately and generated from the original data in a separate image production sequence.
drawImage
This method returns immediately in all cases, even if the image area to be drawn has not yet been scaled, dithered, and converted for the current output device. If the current output representation is not yet complete then drawImage returns false . As more of the image becomes available, the process that loads the image notifies the specified image observer.
This method always uses the unscaled version of the image to render the scaled rectangle and performs the required scaling on the fly. It does not use a cached, scaled version of the image for this operation. Scaling of the image from source to destination is performed such that the first coordinate of the source rectangle is mapped to the first coordinate of the destination rectangle, and the second source coordinate is mapped to the second destination coordinate. The subimage is scaled and flipped as needed to preserve those mappings.
drawImage
Transparent pixels are drawn in the specified background color. This operation is equivalent to filling a rectangle of the width and height of the specified image with the given color and then drawing the image on top of it, but possibly more efficient.
This method returns immediately in all cases, even if the image area to be drawn has not yet been scaled, dithered, and converted for the current output device. If the current output representation is not yet complete then drawImage returns false . As more of the image becomes available, the process that loads the image notifies the specified image observer.
This method always uses the unscaled version of the image to render the scaled rectangle and performs the required scaling on the fly. It does not use a cached, scaled version of the image for this operation. Scaling of the image from source to destination is performed such that the first coordinate of the source rectangle is mapped to the first coordinate of the destination rectangle, and the second source coordinate is mapped to the second destination coordinate. The subimage is scaled and flipped as needed to preserve those mappings.
dispose
When a Java program runs, a large number of Graphics objects can be created within a short time frame. Although the finalization process of the garbage collector also disposes of the same system resources, it is preferable to manually free the associated resources by calling this method rather than to rely on a finalization process which may not run to completion for a long period of time.
Graphics objects which are provided as arguments to the paint and update methods of components are automatically released by the system when those methods return. For efficiency, programmers should call dispose when finished using a Graphics object only if it was created directly from a component or another Graphics object.
finalize
toString
getClipRect
hitClip
getClipBounds
- Summary:
- Nested |
- Field |
- Constr |
- Method
- Detail:
- Field |
- Constr |
- Method
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2021, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.
Источник