1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
SOURCE = "~/Images/Nadar _Sarah_Bernhardt.png"
TARGET = "~/Images/target.png"
CENTER = 620, 400
RADIUS = 200
def get_support():
"""Create the pixmap support for the texture.
Returns:
QPixmap square filled transparent
"""
color = QtGui.QColor()
color.setRgb(0, 0, 0, 0)
pix = QtGui.QPixmap(QtCore.QSize(RADIUS*2, RADIUS*2))
pix.fill(color)
return pix
def draw_path(pix):
"""Draw a circular path into the pixmap.
"""
painter = QtGui.QPainter()
painter.begin(pix)
rect = QtCore.QRectF(1, 1, RADIUS*2-2, RADIUS*2-2)
path = QtGui.QPainterPath()
path.addEllipse(rect)
painter.drawPath(path)
painter.end()
return path
def fill_circle(pix, path, texture):
"""Draw the texture into the shape 'path'.
"""
painter = QtGui.QPainter()
brush = QtGui.QBrush()
brush.setTexture(texture)
painter.begin(pix)
painter.fillPath(path, brush)
painter.end()
def get_texture(base):
"""Returns the sub-region of image at the current coordinate.
Returns:
QPixmap
"""
texture = QtGui.QPixmap(QtCore.QSize(RADIUS*2, RADIUS*2))
irect = QtCore.QRect(CENTER[0]-RADIUS, CENTER[1]-RADIUS,
RADIUS*2, RADIUS*2)
prect = QtCore.QRect(0, 0, RADIUS*2, RADIUS*2)
painter = QtGui.QPainter()
painter.begin(texture)
painter.drawImage(prect, base, irect)
painter.end()
return texture
def main():
image = QtGui.QImage(SOURCE)
support = get_support()
circle = draw_path(support)
texture = get_texture(image)
fill_circle(support, circle, texture)
support.save(TARGET)
if __name__ == "__main__":
app = QtWidgets.QApplication([])
main() |
Partager