xiao-huihui

QML圆形图像的制作与图像置灰效果

在用QML开发界面时,往往我们想将一个方形的图片显示成圆形,类似于早期QQ的圆形图像,许多人想到用radius属性与clip属性进行尝试,但是,始终是没有成功,看来Qt还是没有强大到一定程度啊,哈哈哈。接下来我就简单码上几句实现圆形图像的方法,以及将彩色图像置灰(放QQ离线)的一下方法:
一、将方形图片圆形显示
代码如下:

  1. Rectangle {  
  2.         id: img  
  3.         width: 100  
  4.         height: 100  
  5.         radius: width/2  
  6.         color: "black"  
  7.   
  8.   
  9.         Image {  
  10.             id: _image  
  11.             smooth: true  
  12.             visible: false  
  13.             anchors.fill: parent  
  14.             source: "./testPic.jpg"  
  15.             sourceSize: Qt.size(parent.size, parent.size)  
  16.             antialiasing: true  
  17.         }  
  18.         Rectangle {  
  19.             id: _mask  
  20.             color: "black"  
  21.             anchors.fill: parent  
  22.             radius: width/2  
  23.             visible: false  
  24.             antialiasing: true  
  25.             smooth: true  
  26.         }  
  27.         OpacityMask {  
  28.             id:mask_image  
  29.             anchors.fill: _image  
  30.             source: _image  
  31.             maskSource: _mask  
  32.             visible: true  
  33.             antialiasing: true  
  34.         }  
  35.     }  

对没错,运行OpacityMask可以实现,其参数source和maskSource官方给的解释为:
source : variant
This property defines the source item that is going to be masked.

maskSource : variant
This property defines the item that is going to be used as the mask. The mask item gets rendered into an intermediate pixel buffer and the alpha values from the result are used to determine the source item\'s pixels visibility in the display.
即通过maskSource对source进行遮挡,显示的外观形状为maskSource,内容显示为source的内容,因为上例中的maskSource为Rectangle且radius: width/2,即为圆形,所以显示出来的图片为圆形。
效果如下:



二、将彩色图像置灰
以下介绍如何将上例中的圆形图像编程黑白色(以下代码中的img为上例中的最外层Rectangle)。
代码如下:

  1. Colorize {  
  2.         anchors.fill: img  
  3.         width: 100  
  4.         height: 100  
  5.         source: img  
  6.         hue: 0.0  
  7.         saturation: 0.0  
  8.         lightness: 0.0  
  9.         visible:false  
  10.     }  

是的,通过设置Colorize的色调属性hue、饱和度属性saturation和亮度属性lightness,可以将一个彩色的图片显示成灰色(黑白色),具体各值的变化所代表的意思,请参见Qt的帮助,查询关键字Colorize即可找到。
效果如下:

如果想让离线效果更明显一点,可以将lightness: 0.8即亮度设为0.8,可达到更好的效果,如下:

分类:

技术点:

相关文章: