Что такое blit pygame
Создание поверхностей (Surface), их анимация, метод blit
До сих пор мы с вами выполняли рисование в клиентской области окна, используя переменную sc:
Эта переменная ссылается на класс Surface, который связан с окном всего приложения. Однако, при необходимости, мы можем создать дополнительные поверхности рисования, используя конструктор класса Surface, например, так:
В результате на поверхности sc будет отображена еще одна поверхность surf со всем своим содержимым:
Спрашивается: зачем создавать дополнительный объект surf, когда можно все рисовать непосредственно на основной поверхности sc? Это сделано главным образом для удобства: мы можем на дополнительной поверхности нарисовать сложную графическую информацию, а затем, переносить ее в область главного окна, просто, используя операцию:
Здесь x, y – координаты верхнего левого угла, от которого позиционируется вторая поверхность surf. Затем, достаточно менять в цикле координаты x, y для создания простой анимации нашего графического образа. Перерисовывать каждый раз сложную графическую информацию уже не придется. В этом основное достоинство таких поверхностей.
Класс Surface имеет множество полезных методов. Подробно все их можно посмотреть на странице официальной документации:
Один из них мы уже использовали – это метод:
который отображает содержимое поверхности source на поверхности Surface. Другой весьма полезный метод:
Например, можно сделать так:
Мы здесь определяем две дополнительные поверхности: surf и surf_alpha. Причем, surf_alpha полупрозрачная и располагается на surf. В итоге, имеем такую иерархию поверхностей:
И обратите внимание на такой эффект: поверхность surf_alpha по ширине больше, чем surf. Но, так как surf является родителем для surf_alpha, то все, что выходит за пределы surf – обрезается. В результате, мы видим следующее отображение:
Вот так можно создавать иерархию объектов Surface в PyGame. Причем, если поменять порядок следования слоев:
То поверхность surf также будет отображаться как полупрозрачная – она унаследует это свойство от родителя surf_alpha:
В заключение этого занятия я приведу небольшую программу простой анимации поверхностей (слоев):
Здесь создается два слоя: surf и bita, причем bita рисуется на surf, а surf уже на основной поверхности sc. Далее, в цикле слой surf смещается вниз на 1 пиксель за итерацию, а слой bita на 5 пикселей по горизонтали. После запуска программы мы видим, что слой bita смещается относительно surf, а слой surf движется относительно основного слоя sc. Этот простой пример показывает как можно создавать более сложную анимацию с использованием поверхностей.
Видео по теме
Что такое Pygame? Каркас приложения, FPS | Pygame #1
Рисование графических примитивов | Pygame #2
Как обрабатывать события от клавиатуры | Pygame #3
Как обрабатывать события от мыши | Pygame #4
Создание поверхностей (Surface) и их анимация. Метод blit | Pygame #5
Класс Rect. Его роль, свойства и методы | Pygame #6
Как рисовать текст различными шрифтами | Pygame #7
Как работать с изображениями. Модули image и transform | Pygame #8
Что такое спрайты и как с ними работать | Pygame #9
Как делать контроль столкновений | Pygame #10
Добавляем звук в игровой процесс. Модули mixer и music | Pygame #11
© 2021 Частичное или полное копирование информации с данного сайта для распространения на других ресурсах, в том числе и бумажных, строго запрещено. Все тексты и изображения являются собственностью сайта
Что такое blit pygame
A pygame Surface is used to represent any image. The Surface has a fixed resolution and pixel format. Surfaces with 8-bit pixels use a color palette to map to 24-bit color.
Call pygame.Surface() pygame object for representing images to create a new image object. The Surface will be cleared to all black. The only required arguments are the sizes. With no additional arguments, the Surface will be created in a format that best matches the display Surface.
The pixel format can be controlled by passing the bit depth or an existing Surface. The flags argument is a bitmask of additional features for the surface. You can pass any combination of these flags:
Both flags are only a request, and may not be possible for all displays and formats.
Advance users can combine a set of bitmasks with a depth value. The masks are a set of 4 integers representing which bits in a pixel will represent each color. Normal Surfaces should not require the masks argument.
Surfaces can have many extra attributes like alpha planes, colorkeys, source rectangle clipping. These functions mainly effect how the Surface is blitted to other Surfaces. The blit routines will attempt to use hardware acceleration when possible, otherwise they will use highly optimized software blitting methods.
There are three types of transparency supported in pygame: colorkeys, surface alphas, and pixel alphas. Surface alphas can be mixed with colorkeys, but an image with per pixel alphas cannot use the other modes. Colorkey transparency makes a single color value transparent. Any pixels matching the colorkey will not be drawn. The surface alpha value is a single value that changes the transparency for the entire image. A surface alpha of 255 is opaque, and a value of 0 is completely transparent.
Per pixel alphas are different because they store a transparency value for every pixel. This allows for the most precise transparency effects, but it also the slowest. Per pixel alphas cannot be mixed with surface alpha and colorkeys.
Any functions that directly access a surface’s pixel data will need that surface to be lock()’ed. These functions can lock() and unlock() the surfaces themselves without assistance. But, if a function will be called many times, there will be a lot of overhead for multiple locking and unlocking of the surface. It is best to lock the surface manually before making the function call many times, and then unlocking when you are finished. All functions that need a locked surface will say so in their docs. Remember to leave the Surface locked only while necessary.
Surface pixels are stored internally as a single number that has all the colors encoded into it. Use the map_rgb() and unmap_rgb() to convert between individual red, green, and blue values into a packed integer for that Surface.
Surfaces can also reference sections of other Surfaces. These are created with the subsurface() method. Any change to either Surface will effect the other.
Each Surface contains a clipping area. By default the clip area covers the entire Surface. If it is changed, all drawing operations will only effect the smaller area.
Draws a source Surface onto this Surface. The draw can be positioned with the dest argument. The dest argument can either be a pair of coordinates representing the position of the upper left corner of the blit or a Rect, where the upper left corner of the rectangle will be used as the position for the blit. The size of the destination rectangle does not effect the blit.
An optional area rectangle can be passed as well. This represents a smaller portion of the source Surface to draw.
New in pygame 1.9.2: Optional special_flags : BLEND_PREMULTIPLIED
The return rectangle is the area of the affected pixels, excluding any pixels outside the destination Surface, or outside the clipping area.
Pixel alphas will be ignored when blitting to an 8 bit Surface.
For a surface with colorkey or blanket alpha, a blit to self may give slightly different colors than a non self-blit.
Creates a new copy of the Surface with the pixel format changed. The new pixel format can be determined from another existing Surface. Otherwise depth, flags, and masks arguments can be used, similar to the pygame.Surface() pygame object for representing images call.
If no arguments are passed the new Surface will have the same pixel format as the display Surface. This is always the fastest format for blitting. It is a good idea to convert all Surfaces before they are blitted many times.
The converted Surface will have no pixel alphas. They will be stripped if the original had them. See convert_alpha() for preserving or creating per-pixel alphas.
The new copy will have the same class as the copied surface. This lets as Surface subclass inherit this method without the need to override, unless subclass specific instance attributes also need copying.
Creates a new copy of the surface with the desired pixel format. The new surface will be in a format suited for quick blitting to the given format with per pixel alpha. If no surface is given, the new surface will be optimized for blitting to the current display.
Unlike the convert() method, the pixel format for the new image will not be exactly the same as the requested source, but it will be optimized for fast alpha blitting to the destination.
As with convert() the returned surface has the same class as the converted surface.
Fill the Surface with a solid color. If no rect argument is given the entire Surface will be filled. The rect argument will limit the fill to a specific area. The fill will also be contained by the Surface clip area.
This will return the affected Surface area.
Move the image by dx pixels right and dy pixels down. dx and dy may be negative for left and up scrolls respectively. Areas of the surface that are not overwritten retain their original pixel values. Scrolling is contained by the Surface clip area. It is safe to have dx and dy values that exceed the surface size.
Set the current color key for the Surface. When blitting this Surface onto a destination, any pixels that have the same color as the colorkey will be transparent. The color can be an RGB color or a mapped color integer. If None is passed, the colorkey will be unset.
The colorkey will be ignored if the Surface is formatted to use per pixel alpha values. The colorkey can be mixed with the full Surface alpha value.
The optional flags argument can be set to pygame.RLEACCEL to provide better performance on non accelerated displays. An RLEACCEL Surface will be slower to modify, but quicker to blit as a source.
Return the current colorkey value for the Surface. If the colorkey is not set then None is returned.
Set the current alpha value for the Surface. When blitting this Surface onto a destination, the pixels will be drawn slightly transparent. The alpha value is an integer from 0 to 255, 0 is fully transparent and 255 is fully opaque. If None is passed for the alpha value, then alpha blending will be disabled, including per-pixel alpha.
This value is different than the per pixel Surface alpha. For a surface with per pixel alpha, blanket alpha is ignored and None is returned.
Changed in pygame 2.0: per-surface alpha can be combined with per-pixel alpha.
The optional flags argument can be set to pygame.RLEACCEL to provide better performance on non accelerated displays. An RLEACCEL Surface will be slower to modify, but quicker to blit as a source.
Return the current alpha value for the Surface.
Lock the pixel data of a Surface for access. On accelerated Surfaces, the pixel data may be stored in volatile video memory or nonlinear compressed forms. When a Surface is locked the pixel memory becomes available to access by regular software. Code that reads or writes pixel values will need the Surface to be locked.
Surfaces should not remain locked for more than necessary. A locked Surface can often not be displayed or managed by pygame.
Not all Surfaces require locking. The mustlock() method can determine if it is actually required. There is no performance penalty for locking and unlocking a Surface that does not need it.
All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.
It is safe to nest locking and unlocking calls. The surface will only be unlocked after the final lock is released.
Unlock the Surface pixel data after it has been locked. The unlocked Surface can once again be drawn and managed by pygame. See the lock() documentation for more details.
All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.
It is safe to nest locking and unlocking calls. The surface will only be unlocked after the final lock is released.
Returns True if the Surface is required to be locked to access pixel data. Usually pure software Surfaces do not require locking. This method is rarely needed, since it is safe and quickest to just lock all Surfaces as needed.
All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.
Returns True when the Surface is locked. It doesn’t matter how many times the Surface is locked.
Returns the currently existing locks for the Surface.
Return a copy of the RGBA Color value at the given pixel. If the Surface has no per pixel alpha, then the alpha value will always be 255 (opaque). If the pixel position is outside the area of the Surface an IndexError exception will be raised.
This function will temporarily lock and unlock the Surface as needed.
New in pygame 1.9: Returning a Color instead of tuple. Use tuple(surf.get_at((x,y))) if you want a tuple, and not a Color. This should only matter if you want to use the color as a key in a dict.
Set the RGBA or mapped integer color value for a single pixel. If the Surface does not have per pixel alphas, the alpha value is ignored. Setting pixels outside the Surface area or outside the Surface clipping will have no effect.
Getting and setting pixels one at a time is generally too slow to be used in a game or realtime situation.
This function will temporarily lock and unlock the Surface as needed.
Return the integer value of the given pixel. If the pixel position is outside the area of the Surface an IndexError exception will be raised.
This method is intended for pygame unit testing. It unlikely has any use in an application.
This function will temporarily lock and unlock the Surface as needed.
Return a list of up to 256 color elements that represent the indexed colors used in an 8-bit Surface. The returned list is a copy of the palette, and changes will have no effect on the Surface.
Returning a list of Color(with length 3) instances instead of tuples.
Returns the red, green, and blue color values for a single index in a Surface palette. The index should be a value from 0 to 255.
New in pygame 1.9: Returning Color(with length 3) instance instead of a tuple.
Set the full palette for an 8-bit Surface. This will replace the colors in the existing palette. A partial palette can be passed and only the first colors in the original palette will be changed.
This function has no effect on a Surface with more than 8-bits per pixel.
Set the palette value for a single entry in a Surface palette. The index should be a value from 0 to 255.
This function has no effect on a Surface with more than 8-bits per pixel.
Convert an RGBA color into the mapped integer value for this Surface. The returned integer will contain no more bits than the bit depth of the Surface. Mapped color values are not often used inside pygame, but can be passed to most functions that require a Surface and a color.
See the Surface object documentation for more information about colors and pixel formats.
Convert an mapped integer color into the RGB color components for this Surface. Mapped color values are not often used inside pygame, but can be passed to most functions that require a Surface and a color.
See the Surface object documentation for more information about colors and pixel formats.
Each Surface has an active clipping area. This is a rectangle that represents the only pixels on the Surface that can be modified. If None is passed for the rectangle the full Surface will be available for changes.
The clipping area is always restricted to the area of the Surface itself. If the clip rectangle is too large it will be shrunk to fit inside the Surface.
Return a rectangle of the current clipping area. The Surface will always return a valid rectangle that will never be outside the bounds of the image. If the Surface has had None set for the clipping area, the Surface will return a rectangle with the full area of the Surface.
Returns a new Surface that shares its pixels with its new parent. The new Surface is considered a child of the original. Modifications to either Surface pixels will effect each other. Surface information like clipping area and color keys are unique to each Surface.
The new Surface will inherit the palette, color key, and alpha settings from its parent.
It is possible to have any number of subsurfaces and subsubsurfaces on the parent. It is also possible to subsurface the display Surface if the display mode is not hardware accelerated.
See get_offset() and get_parent() to learn more about the state of a subsurface.
A subsurface will have the same class as the parent surface.
Returns the parent Surface of a subsurface. If this is not a subsurface then None will be returned.
Returns the parent Surface of a subsurface. If this is not a subsurface then this surface will be returned.
Get the offset position of a child subsurface inside of a parent. If the Surface is not a subsurface this will return (0, 0).
Get the offset position of a child subsurface inside of its top level parent Surface. If the Surface is not a subsurface this will return (0, 0).
Return the width and height of the Surface in pixels.
Return the width of the Surface in pixels.
Return the height of the Surface in pixels.
Returns a new rectangle covering the entire surface. This rectangle will always start at (0, 0) with a width and height the same size as the image.
You can pass keyword argument values to this function. These named values will be applied to the attributes of the Rect before it is returned. An example would be mysurf.get_rect(center=(100, 100)) to create a rectangle for the Surface centered at a given position.
Returns the number of bits used to represent each pixel. This value may not exactly fill the number of bytes used per pixel. For example a 15 bit Surface still requires a full 2 bytes.
Return the number of bytes used per pixel.
Here is a more complete list of flags. A full list can be found in SDL_video.h
Used internally (read-only)
Return the number of bytes separating each row in the Surface. Surfaces in video memory are not always linearly packed. Subsurfaces will also have a larger pitch than their real width.
This value is not needed for normal pygame usage.
Returns the bitmasks used to isolate each color in a mapped integer.
This value is not needed for normal pygame usage.
This is not needed for normal pygame usage.
In SDL2, the masks are read-only and accordingly this method will raise an AttributeError if called.
Returns the pixel shifts need to convert between each color and a mapped integer.
This value is not needed for normal pygame usage.
This is not needed for normal pygame usage.
In SDL2, the shifts are read-only and accordingly this method will raise an AttributeError if called.
Return the least significant number of bits stripped from each color in a mapped integer.
This value is not needed for normal pygame usage.
Returns the smallest rectangular region that contains all the pixels in the surface that have an alpha value greater than or equal to the minimum alpha value.
This function will temporarily lock and unlock the Surface as needed.
Return an object which exports a surface’s internal pixel buffer as a C level array struct, Python level array interface or a C level buffer interface. The pixel buffer is writeable. The new buffer protocol is supported for Python 2.6 and up in CPython. The old buffer protocol is also supported for Python 2.x. The old buffer data is in one segment for kind ‘0’, multi-segment for other buffer view kinds.
The kind argument is the length 1 string ‘0’, ‘1’, ‘2’, ‘3’, ‘r’, ‘g’, ‘b’, or ‘a’. The letters are case insensitive; ‘A’ will work as well. The argument can be either a Unicode or byte (char) string. The default is ‘2’.
‘0’ returns a contiguous unstructured bytes view. No surface shape information is given. A ValueError is raised if the surface’s pixels are discontinuous.
‘1’ returns a (surface-width * surface-height) array of continuous pixels. A ValueError is raised if the surface pixels are discontinuous.
‘2’ returns a (surface-width, surface-height) array of raw pixels. The pixels are surface-bytesize-d unsigned integers. The pixel format is surface specific. The 3 byte unsigned integers of 24 bit surfaces are unlikely accepted by anything other than other pygame functions.
‘3’ returns a (surface-width, surface-height, 3) array of RGB color components. Each of the red, green, and blue components are unsigned bytes. Only 24-bit and 32-bit surfaces are supported. The color components must be in either RGB or BGR order within the pixel.
‘r’ for red, ‘g’ for green, ‘b’ for blue, and ‘a’ for alpha return a (surface-width, surface-height) view of a single color component within a surface: a color plane. Color components are unsigned bytes. Both 24-bit and 32-bit surfaces support ‘r’, ‘g’, and ‘b’. Only 32-bit surfaces with SRCALPHA support ‘a’.
The surface is locked only when an exposed interface is accessed. For new buffer interface accesses, the surface is unlocked once the last buffer view is released. For array interface and old buffer interface accesses, the surface remains locked until the BufferProxy object is released.
Return a buffer object for the pixels of the Surface. The buffer can be used for direct pixel access and manipulation. Surface pixel data is represented as an unstructured block of memory, with a start address and length in bytes. The data need not be contiguous. Any gaps are included in the length, but otherwise ignored.
This method implicitly locks the Surface. The lock will be released when the returned pygame.BufferProxy pygame object to export a surface buffer through an array protocol object is garbage collected.
The starting address of the surface’s raw pixel bytes.
Немного запутался с блитирование (с которым Pygame)
Я только начал изучать pygame (совершенно новый для программирования в целом), и у меня есть некоторые очень простые вопросы о том, как это работает.
Я еще не нашел место, которое объясняет, когда мне нужно blit или не включать определенную поверхность на экране. Например, при рисовании круга:
Если я не blit, текст не появится.
честно говоря, я действительно не знаю, что блитинг должен делать, кроме «вставки» желаемой поверхности на экран. Надеюсь, я достаточно ясно выразился.
3 ответов
короткий ответ:
Я еще не нашел место, которое объясняет, когда мне нужно blit или не включать определенную поверхность на экране.
каждая операция будет вести себя по-разному, и вам нужно будет прочитать документацию для функции, с которой вы работаете.
долгий ответ
Что Такое Блиттинг?
во-первых, вам нужно понять, что делает blitting. Ваш экран-это просто набор пикселей, и blitting делает полную копию одного набора пикселей на другой. Например, вы можете иметь поверхность с изображением, которое вы загрузили с жесткого диска, и можете отображать его несколько раз на экране в разных положениях, стирая эту поверхность поверх screen поверхность несколько раз.
Итак, у вас часто есть такой код.
в двух строках кода мы скопировали тонну пикселей с исходной поверхности (my_image) на экран с помощью «блитирование».
как сделать pygame.рисовать.* функции blit?
технически, pygame.рисовать.* методы могли быть написаны, чтобы сделать что-то подобное. Итак, вместо вашего примера.
. они могли заставить тебя сделать это.
если бы это было так, вы бы получили тот же результат. Внутренне, однако, pygame.draw.circle() метод непосредственно манипулирует поверхностью, которую вы передаете ей, а не создает новую поверхность. Это могло бы был выбран как способ делать вещи, потому что они могли бы работать быстрее или с меньшим объемом памяти, чем создание новой поверхности.
так что мне делать?
Итак, на ваш вопрос «когда блить» и «когда нет», в основном, вам нужно прочитать документацию, чтобы увидеть, что функция на самом деле делает.
нарисуйте круг вокруг точка
обратите внимание, что он говорит, что «рисует фигуру на поверхности», поэтому он уже сделал изменения пиксела для вас. Кроме того, он не возвращает поверхность (it возвращает прямую кишку, но это просто говорит вам, где были сделаны изменения пикселей).
нарисуйте текст на новой поверхности
как вы можете видеть, в нем конкретно говорится, что текст рисуется на новой поверхности, которая создается и возвращается вам. Эта поверхность не является поверхностью вашего экрана (это не может быть, вы даже не сказали
Blit означает ‘BL’ock’ i’Mage ‘ t’ranfser
когда вы показываете вещи на экране, вы будете, в некотором роде, использовать screen потому что именно туда вы его помещаете.
вы все еще используете экран, но вы просто не blitting, потому что pygame рисует его для вас.
и когда вы используете текст, pygame отображает его в изображение, тогда вам нужно его уничтожить.
Так что в основном вы blit изображения, но вы можете также у pygame нарисуйте их для вас. Но помните, когда вы стираете изображение, скажем, на фоне, вам нужно зациклить его назад и в-четвертых; так что он стирает фон, затем изображение, затем фон и т. д.
надеюсь, это помогло. Удачи!
представьте, что вы художник:
У вас есть холст и кисти.
когда вы называете blit, вы рисуете сверху поверхности, покрывающей любые перекрывающиеся пиксели. Вот почему вам нужно перекрасить весь экран в черный цвет, чтобы у вас не было никаких пятен на картине в то время как перемещение объекта.
Как уже сказал Марк, вы можете нарисовать круг с функцией, или сначала Блит его на новую поверхность, и Блит, что на поверхности экрана.