Java android app graphics

Графика

Пакет android.graphics имеет все необходимые библиотеки для работы с двухмерной графикой. Существует несколько подходов для рисования графики.

Для рисования простой графики, которая не будет динамически изменяться во время работы приложения, обычно используют класс, наследующий от View и задействуют метод onDraw().

В метод передаётся объект Canvas, у которого есть различные графические методы.

Стандартная реализация подобного подхода выглядит следующим образом:

 public class ViewGraphicsActivity extends Activity < @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(new MyView(this)); >> 

В методе setContentView() вместо ссылки на разметку передаётся класс MyView, наследующий от View:

 class MyView extends View < public MyView(Context context) < super(context); >@Override public void onDraw(Canvas canvas) < >> 

В методе onDraw() можете рисовать:

 Paint paint = new Paint(); paint.setColor(Color.WHITE); paint.setTextSize(20); paint.setAntiAlias(true); canvas.drawColor(Color.BLUE); canvas.drawText("Hello Kitty", 10, 20, paint); Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); canvas.drawBitmap(image, 40, 80, null); 

Для рисования динамической графики больше подойдёт класс SurfaceView, имеющий дополнительные возможности. Данному классу мы посвятим отдельный материал.

Класс Color

Класс Color отвечает за цвета. Цвета можно описывать четырьмя числами в формате ARGB, по одному для каждого канала(Alpha, Red, Green, Blue).

Класс Paint

Класс Paint содержит стили, цвета и другую графическую информацию для рисования графических объектов. Он позволяет выбирать способ отображения графических примитивов, которые вы рисуете на объекте Canvas с помощью методов. Изменяя объект Paint, можно контролировать цвет, стиль, шрифт и специальные эффекты, используемые при рисовании. Например, чтобы установить сплошной цвет для рисования линии, нужно вызвать метод Paint.setColor().

В этом примере мы использовали готовую константу. Также можно указать 32-битное целое число, закодированное в схеме ARGB8888.

Можно установить цвет через его составляющие:

 mPaint.setARGB(alpha, red, green, blue); 

Стиль объекта Paint, задаваемый с помощью метода setStyle(), позволяет рисовать либо очертания графического примитива (STROKE), либо его заливку (FILL), либо и то, и другое сразу (STROKE_AND_FILL).

Помимо этих простых методов класс Paint поддерживает прозрачность и может быть изменён с помощью различных шейдеров, фильтров и эффектов, которые предоставляют богатый набор сложных красок и кистей.

Использование полупрозрачности

Любой цвет в Android содержит свойство прозрачности (альфа-канал). Указать его можно при создании описывающей цвет переменной, используя методы argb() и parseColor():

 // Делаем цвет красным и наполовину прозрачным int opacity = 127; int intColor = Color.argb(opacity, 255, 0, 0); int parsedColor = Color.parseColor("#7FFF0000"); 

Но мы можем задать прозрачность уже существующего объекта Paint с помощью метода setAlpha():

 int opacity = 127; myPaint.setAlpha(opacity); 

Пример использования метода setAlpha() для наложения двух картинок.

Режим Xfermode

Изменение режима Xfermode для объекта Paint влияет на способ наложения новых цветов поверх уже нарисованных. В обычных обстоятельствах при рисовании поверх имеющегося рисунка создастся новый верхний слой. Если новый объект Paint на 100% непрозрачный, он полностью закрасит все, что находится под областью для рисования; если он полупрозрачный, то только затенит лежащие ниже цвета. Подклассы Xfermode позволяют изменить такое поведение.

  • AvoidXfermode. Определяет цвет, поверх которого объект Paint не может (или наоборот — может только поверх него) рисовать. Задается также параметр tolerance, указывающий на допустимое отклонение.
  • PixelXorXfermode. Применяет простое побитовое исключение (XOR) при рисовании поверх существующих цветов.
  • PorterDuffXfermode. Мощный режим, с помощью которого можно использовать любое из шестнадцати правил смешивания изображений Портера-Даффа, управляя процессом наложения кисти на уже существующий рисунок.

Для того чтобы применить один из этих режимов, используйте метод setXferMode():

 AvoidXfermode avoid = new AvoidXfermode(Color.BLUE, 10, AvoidXfermode.Mode.AVOID); borderPen.setXfermode(avoid); 

Сглаживание

При создании нового объекта Paint вы можете передать в его конструктор несколько флагов, которые будут влиять на способ отображения. Одним из наиболее интересных из них считается флаг ANTI_ALIAS_FLAG, обеспечивающий сглаживание диагональных линий, рисуемых объектом Paint (снижая при этом производительность).

Сглаживание играет важную роль в процессе отрисовки текста, значительно упрощает его восприятие. Чтобы сделать текст более гладким, можете использовать флаг SUBPIXEL_TEXT_FLAG, который применяет субпиксельное сглаживание. Можно задать оба этих флага программно, используя методы setSubpixelText() и setAntiAlias():

 myPaint.setSubpixelText(true); myPaint.setAntiAlias(true); 

Класс Path

Класс Path позволяет рисовать контуры разных типов — пунктиры, сглаживание линий и т.д.

Класс Canvas

Класс Canvas представляет собой специальную поверхность (холст), на которой вы можете рисовать. С помощью многочисленных методов класса вы можете рисовать линии, окружности, дуги и так далее.

Класс Bitmap

Класс Bitmap отвечает за растровые картинки.

Источник

Graphics

The Android framework offers a variety of graphics rendering APIs for 2D and 3D that interact with manufacturer implementations of graphics drivers, so it is important to have a good understanding of how those APIs work at a higher level. This page introduces the graphics hardware abstraction layer (HAL) upon which those drivers are built.

Android graphics components

No matter what rendering API developers use, everything is rendered onto a surface. The surface represents the producer side of a buffer queue that is often consumed by SurfaceFlinger. Every window that is created on the Android platform is backed by a surface. All of the visible surfaces rendered are composited onto the display by SurfaceFlinger.

The following diagram shows how the key components work together:

image rendering components

Figure 1. How surfaces are rendered

The main components are described below:

Image Stream Producers

An image stream producer can be anything that produces graphic buffers for consumption. Examples include OpenGL ES, Canvas 2D, and mediaserver video decoders.

Image stream consumers

The most common consumer of image streams is SurfaceFlinger, the system service that consumes the currently visible surfaces and composites them onto the display using information provided by the Window Manager. SurfaceFlinger is the only service that can modify the content of the display. SurfaceFlinger uses OpenGL and the Hardware Composer to compose a group of surfaces.

Other OpenGL ES apps can consume image streams as well, such as the camera app consuming a camera preview image stream. Non-GL applications can be consumers too, for example the ImageReader class.

Hardware Composer

The hardware abstraction for the display subsystem. SurfaceFlinger can delegate certain composition work to the Hardware Composer to offload work from OpenGL and the GPU. SurfaceFlinger acts as just another OpenGL ES client. So when SurfaceFlinger is actively compositing one buffer or two into a third, for instance, it is using OpenGL ES. This makes compositing lower power than having the GPU conduct all computation.

The Hardware Composer HAL conducts the other half of the work and is the central point for all Android graphics rendering. The Hardware Composer must support events, one of which is VSYNC (another is hotplug for plug-and-playHDMI support).

Gralloc

Data flow

See the following diagram for a depiction of the Android graphics pipeline:

graphics data flow

Figure 2. Graphic data flow through Android

The objects on the left are renderers producing graphics buffers, such as the home screen, status bar, and system UI. SurfaceFlinger is the compositor and Hardware Composer is the composer.

BufferQueue

BufferQueues provide the glue between the Android graphics components. These are a pair of queues that mediate the constant cycle of buffers from the producer to the consumer. Once the producers hand off their buffers, SurfaceFlinger is responsible for compositing everything onto the display.

See the following diagram for the BufferQueue communication process.

BufferQueue communication process

Figure 3. BufferQueue communication process

BufferQueue contains the logic that ties image stream producers and image stream consumers together. Some examples of image producers are the camera previews produced by the camera HAL or OpenGL ES games. Some examples of image consumers are SurfaceFlinger or another app that displays an OpenGL ES stream, such as the camera app displaying the camera viewfinder.

BufferQueue can operate in three different modes:

Synchronous-like mode — BufferQueue by default operates in a synchronous-like mode, in which every buffer that comes in from the producer goes out at the consumer. No buffer is ever discarded in this mode. And if the producer is too fast and creates buffers faster than they are being drained, it will block and wait for free buffers.

Non-blocking mode — BufferQueue can also operate in a non-blocking mode where it generates an error rather than waiting for a buffer in those cases. No buffer is ever discarded in this mode either. This is useful for avoiding potential deadlocks in application software that may not understand the complex dependencies of the graphics framework.

Discard mode — Finally, BufferQueue may be configured to discard old buffers rather than generate errors or wait. For instance, if conducting GL rendering to a texture view and drawing as quickly as possible, buffers must be dropped.

To conduct most of this work, SurfaceFlinger acts as just another OpenGL ES client. So when SurfaceFlinger is actively compositing one buffer or two into a third, for instance, it is using OpenGL ES.

The Hardware Composer HAL conducts the other half of the work. This HAL acts as the central point for all Android graphics rendering.

Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Last updated 2022-08-02 UTC.

Источник

Читайте также:  Css style hidden text
Оцените статью