每天学习一个小例子---------原资源已经上传了
来源:
https://pyqt.site , https://github.com/PyQt5
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 2018年1月20日 @author: Irony @site: https://pyqt.site , https://github.com/PyQt5 @email: 892768447@qq.com @file: CircleImage @description: 圆形图片 """ try: from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap, QPainter, QPainterPath from PyQt5.QtWidgets import QLabel, QWidget, QHBoxLayout, QApplication except importError: from PySide2.QtCore import Qt from PySide2.QtGui import QPixmap, QPainter, QPainterPath from PySide2.QtWidgets import QLabel, QWidget, QHBoxLayout, QApplication class Label(QLabel): def __init__(self, *args, antialiasing=True, **kwargs): super(Label, self).__init__(*args, **kwargs) self.Antialiasing = antialiasing # 抗锯齿 self.setMaximumSize(200, 200) self.setMinimumSize(200, 200) self.radius = 100 # 半径 #####################核心实现######################### self.target = QPixmap(self.size()) # 大小和控件一样 self.target.fill(Qt.transparent) # 填充背景为透明 p = QPixmap("Data/Images/head.jpg").scaled( # 加载图片并缩放和控件一样大 200, 200, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation) # KeepAspectRatioByExpanding 通过扩展保持纵横比 # SmoothTransformation 平滑变换 painter = QPainter(self.target) # 在target上画图 if self.Antialiasing: # 抗锯齿 painter.setRenderHint(QPainter.Antialiasing, True) # 设置渲染 抗锯齿 painter.setRenderHint(QPainter.HighQualityAntialiasing, True) # 高质量抗锯齿 painter.setRenderHint(QPainter.SmoothPixmapTransform, True) # 平滑像素映射变换 # painter.setPen(# 测试圆圈 # QPen(Qt.red, 5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) path = QPainterPath() """ QPainterPath类为绘制 *** 作提供了一个容器,可以构造和重用图形形状。 用途:它是由一些图形如曲线、矩形、椭圆组成的对象。主要的用途是,能保存已经绘制好的图形。实现图形元素的构造和复用; 图形状只需创建一次,然后调用QPainter::drawPath()函数多次绘制。 painterpath可以加入闭合或不闭合的图形(如:矩形、椭圆和曲线)。QPainterPath 可用于填充,描边,clipping。 使用方法:QPainterPath一旦创建,直线和曲线都可以被添加入path, 通过lineTo(),arcTo(),cubicTo()和 quadTo()函数。currentPosition()是最后一次绘制后的“结束点”(或初始点)。 使用moveTo()移动currentPosition()而不会添加任何元素。moveTo() 隐含的开始一个新subpath,并且闭合前一个。 一个path 添加到另一个path 用connectPath()。它默认是从原点(0,0)开始绘图,可以使用moveTo()改变绘图的开始位置。 """ path.addRoundedRect( # 添加圆角矩形 0, 0, self.width(), self.height(), self.radius, self.radius) # **** 切割为圆形 ****# painter.setClipPath(path) # painter.drawPath(path) # 测试圆圈 painter.drawPixmap(0, 0, p) self.setPixmap(self.target) #####################核心实现######################### class Window(QWidget): def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) layout = QHBoxLayout(self) layout.addWidget(Label(self)) layout.addWidget(Label(self, antialiasing=False)) self.setStyleSheet("background: black;") if __name__ == "__main__": import sys app = QApplication(sys.argv) w = Window() w.show() sys.exit(app.exec_())
2 图片旋转
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 2018年11月19日 @author: Irony @site: https://pyqt.site , https://github.com/PyQt5 @email: 892768447@qq.com @file: @description: """ try: from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap, QPainter, QImage from PyQt5.QtWidgets import QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout, QSpacerItem, QSizePolicy, QApplication except importError: from PySide2.QtCore import Qt from PySide2.QtGui import QPixmap, QPainter, QImage from PySide2.QtWidgets import QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout, QSpacerItem, QSizePolicy, QApplication class Window(QWidget): def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) layout = QVBoxLayout(self) self.imageLabel = QLabel(self) self.imageLabel.setAlignment(Qt.AlignCenter) #设置对齐---对准中心 layout.addWidget(self.imageLabel) clayout = QHBoxLayout() # 采用QBOXLayout类可以在水平和垂直方向上排列控件,QHBoxLayout和QVBoxLayout类继承自QBoxLayout # 采用QHBoxLayout类,按照从左到右的顺序来添加控件 layout.addItem(clayout) # 添加项 clayout.addItem(QSpacerItem( # d簧 间隔项 40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)) # 添加按钮 clayout.addWidget(QPushButton('水平翻转', self, clicked=self.doHorFilp)) clayout.addWidget(QPushButton('垂直翻转', self, clicked=self.doVerFilp)) clayout.addWidget(QPushButton( '顺时针45度', self, clicked=self.doClockwise)) clayout.addWidget(QPushButton( '逆时针45度', self, clicked=self.doAnticlockwise)) clayout.addItem(QSpacerItem( 40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)) # 原始图片 self.srcImage = QImage('Data/fg.png') self.imageLabel.setPixmap(QPixmap.fromImage(self.srcImage)) def doHorFilp(self): # 水平翻转 self.srcImage = self.srcImage.mirrored(True, False) # 镜像 self.imageLabel.setPixmap(QPixmap.fromImage(self.srcImage)) def doVerFilp(self): # 垂直翻转 self.srcImage = self.srcImage.mirrored(False, True) self.imageLabel.setPixmap(QPixmap.fromImage(self.srcImage)) def doClockwise(self): # 顺时针45度 image = QImage(self.srcImage.size(), QImage.Format_ARGB32_Premultiplied) painter = QPainter() # 创建绘图容器 painter.begin(image) # 以图片中心为原点 hw = self.srcImage.width() / 2 hh = self.srcImage.height() / 2 painter.translate(hw, hh) painter.rotate(45) # 旋转45度 painter.drawImage(-hw, -hh, self.srcImage) # 把图片绘制上去 painter.end() self.srcImage = image # 替换 self.imageLabel.setPixmap(QPixmap.fromImage(self.srcImage)) # # 下面这个旋转方法针对90度的倍数,否则图片会变大 # trans = QTransform() # trans.rotate(90) # self.srcImage = self.srcImage.transformed( # trans, Qt.SmoothTransformation) # self.imageLabel.setPixmap(QPixmap.fromImage(self.srcImage)) def doAnticlockwise(self): # 逆时针45度 image = QImage(self.srcImage.size(), QImage.Format_ARGB32_Premultiplied) painter = QPainter() painter.begin(image) # 以图片中心为原点 hw = self.srcImage.width() / 2 hh = self.srcImage.height() / 2 painter.translate(hw, hh) painter.rotate(-45) # 旋转-45度 painter.drawImage(-hw, -hh, self.srcImage) # 把图片绘制上去 painter.end() self.srcImage = image # 替换 self.imageLabel.setPixmap(QPixmap.fromImage(self.srcImage)) # # 下面这个旋转方法针对90度的倍数,否则图片会变大 # trans = QTransform() # trans.rotate(90) # self.srcImage = self.srcImage.transformed( # trans, Qt.SmoothTransformation) # self.imageLabel.setPixmap(QPixmap.fromImage(self.srcImage)) if __name__ == '__main__': import sys app = QApplication(sys.argv) w = Window() w.show() sys.exit(app.exec_())
3 仿网页图片错位显示
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 2018年10月18日 @author: Irony @site: https://pyqt.site , https://github.com/PyQt5 @email: 892768447@qq.com @file: ImageSlipped @description: """ try: from PyQt5.QtGui import QPixmap, QPainter from PyQt5.QtWidgets import QWidget, QApplication except importError: from PySide2.QtGui import QPixmap, QPainter from PySide2.QtWidgets import QWidget, QApplication class SlippedImgWidget(QWidget): def __init__(self, bg, fg, *args, **kwargs): super(SlippedImgWidget, self).__init__(*args, **kwargs) # 开启鼠标跟踪 self.setMouseTracking(True) # 背景 self.bgPixmap = QPixmap(bg) # 前景 self.pePixmap = QPixmap(fg) # 最小尺寸(背景右边和下方隐藏10个像素) size = self.bgPixmap.size() self.setMinimumSize(size.width() - 10, size.height() - 10) self.setMaximumSize(size.width() - 10, size.height() - 10) # 分成10份用于鼠标移动判断 self.stepX = size.width() / 10 self.stepY = size.height() / 10 # 偏移量 self._offsets = [-4, -4, -4, -4] # 背景(-4,-4),前景(-4,-4) def mouseMoveEvent(self, event): super(SlippedImgWidget, self).mouseMoveEvent(event) pos = event.pos() # 偏移量 offsetX = 5 - int(pos.x() / self.stepX) offsetY = 5 - int(pos.y() / self.stepY) self._offsets[0] = offsetX self._offsets[1] = offsetY self._offsets[2] = offsetX self._offsets[3] = offsetY # 刷新 self.update() def paintEvent(self, event): super(SlippedImgWidget, self).paintEvent(event) # 绘制图形 painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) # 左上角偏移5个像素画背景图片 painter.drawPixmap( -5 + self._offsets[0], -5 + self._offsets[1], self.bgPixmap) # 右下角偏移5个像素画前景图片 painter.drawPixmap( self.width() - self.pePixmap.width() + 5 - self._offsets[2], self.height() - self.pePixmap.height() + 5 - self._offsets[3], self.pePixmap ) if __name__ == '__main__': import sys app = QApplication(sys.argv) w = SlippedImgWidget('Data/bg1.jpg', 'Data/fg1.png') w.show() sys.exit(app.exec_())
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 2018年10月25日 @author: Irony @site: https://pyqt.site , https://github.com/PyQt5 @email: 892768447@qq.com @file: NinePatch @description: """ import sys try: from PyQt5.QtGui import QPainter from PyQt5.QtWidgets import QApplication, QWidget except importError: from PySide2.QtGui import QPainter from PySide2.QtWidgets import QApplication, QWidget from Lib.NinePatch import NinePatch class Label(QWidget): def __init__(self, *args, **kwargs): super(Label, self).__init__(*args, **kwargs) # .9 格式的图片 self.image = NinePatch('Data/skin_aio_friend_bubble_pressed.9.png') def paintEvent(self, event): super(Label, self).paintEvent(event) painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.SmoothPixmapTransform) try: self.image.SetImageSize(self.width(), self.height()) self.image.Draw(painter, 0, 0) except Exception as e: print(e) app = QApplication(sys.argv) w = Label() w.resize(400, 200) w.show() sys.exit(app.exec_())
5
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 2017年12月23日 @author: Irony @site: https://pyqt.site , https://github.com/PyQt5 @email: 892768447@qq.com @file: ShowImage @description: """ import sys try: from PyQt5.QtCore import QResource from PyQt5.QtGui import QPixmap, QMovie from PyQt5.QtWidgets import QWidget, QApplication, QHBoxLayout, QLabel except importError: from PySide2.QtCore import QResource from PySide2.QtGui import QPixmap, QMovie from PySide2.QtWidgets import QWidget, QApplication, QHBoxLayout, QLabel from Lib.xpmres import image_head # @Unresolvedimport class ImageView(QWidget): def __init__(self, *args, **kwargs): super(ImageView, self).__init__(*args, **kwargs) self.resize(800, 600) layout = QHBoxLayout(self) # 从文件加载图片 layout.addWidget(QLabel(self, pixmap=QPixmap("Data/head.jpg"))) # QResource 参考 http://doc.qt.io/qt-5/resources.html # 从资源文件中加载1 from py file # 转换命令pyrcc5 res.qrc -o res_rc.py # 这种方式是从通过pyrcc5转换res.qrc为res_rc.py文件,可以直接import加载 # 此时可以通过路径:/images/head.jpg来访问 layout.addWidget(QLabel(self, pixmap=QPixmap(":/images/head.jpg"))) # 从二进制资源文件res.rcc中加载 # 转换命令tools/rcc.exe -binary res2.qrc -o res.rcc # 这里把资源前缀修改下(/myfile),见res2.qrc文件 # 此时需要注册 QResource.registerResource("Data/res.rcc") # 注意前缀 layout.addWidget( QLabel(self, pixmap=QPixmap(":/myfile/images/head.jpg"))) # 从xpm数组中加载 # 通过工具tools/Image2XPM.exe来转换 # 这里把转换的xpm数组直接放到py文件中当做一个变量 # 见xpmres.py中的image_head layout.addWidget(QLabel(self, pixmap=QPixmap(image_head))) # 加载gif图片 movie = QMovie("Data/loading.gif") label = QLabel(self) label.setMovie(movie) layout.addWidget(label) movie.start() if __name__ == "__main__": app = QApplication(sys.argv) w = ImageView() w.show() sys.exit(app.exec_())
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)