1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtQml module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qquickborderimage_p.h"
43 #include "qquickborderimage_p_p.h"
45 #include <QtQml/qqmlinfo.h>
46 #include <QtQml/qqmlfile.h>
47 #include <QtQml/qqmlengine.h>
48 #include <QtNetwork/qnetworkreply.h>
49 #include <QtCore/qfile.h>
51 #include <private/qqmlglobal_p.h>
57 \qmlclass BorderImage QQuickBorderImage
58 \inqmlmodule QtQuick 2
59 \brief Paints a border based on an image
61 \ingroup qtquick-visual
63 The BorderImage type is used to create borders out of images by scaling or tiling
66 A BorderImage breaks a source image, specified using the \l source property,
67 into 9 regions, as shown below:
69 \image declarative-scalegrid.png
71 When the image is scaled, regions of the source image are scaled or tiled to
72 create the displayed border image in the following way:
75 \li The corners (regions 1, 3, 7, and 9) are not scaled at all.
76 \li Regions 2 and 8 are scaled according to
77 \l{BorderImage::horizontalTileMode}{horizontalTileMode}.
78 \li Regions 4 and 6 are scaled according to
79 \l{BorderImage::verticalTileMode}{verticalTileMode}.
80 \li The middle (region 5) is scaled according to both
81 \l{BorderImage::horizontalTileMode}{horizontalTileMode} and
82 \l{BorderImage::verticalTileMode}{verticalTileMode}.
85 The regions of the image are defined using the \l border property group, which
86 describes the distance from each edge of the source image to use as a border.
88 \section1 Example Usage
90 The following examples show the effects of the different modes on an image.
91 Guide lines are overlaid onto the image to show the different regions of the
92 image as described above.
95 \image qml-borderimage-normal-image.png
98 An unscaled image is displayed using an Image. The \l border property is
99 used to determine the parts of the image that will lie inside the unscaled corner
100 areas and the parts that will be stretched horizontally and vertically.
102 \snippet qml/borderimage/normal-image.qml normal image
106 \image qml-borderimage-scaled.png
109 A BorderImage is used to display the image, and it is given a size that is
110 larger than the original image. Since the \l horizontalTileMode property is set to
111 \l{BorderImage::horizontalTileMode}{BorderImage.Stretch}, the parts of image in
112 regions 2 and 8 are stretched horizontally. Since the \l verticalTileMode property
113 is set to \l{BorderImage::verticalTileMode}{BorderImage.Stretch}, the parts of image
114 in regions 4 and 6 are stretched vertically.
116 \snippet qml/borderimage/borderimage-scaled.qml scaled border image
120 \image qml-borderimage-tiled.png
123 Again, a large BorderImage is used to display the image. With the
124 \l horizontalTileMode property set to \l{BorderImage::horizontalTileMode}{BorderImage.Repeat},
125 the parts of image in regions 2 and 8 are tiled so that they fill the space at the
126 top and bottom of the item. Similarly, the \l verticalTileMode property is set to
127 \l{BorderImage::verticalTileMode}{BorderImage.Repeat}, the parts of image in regions
128 4 and 6 are tiled so that they fill the space at the left and right of the item.
130 \snippet qml/borderimage/borderimage-tiled.qml tiled border image
133 In some situations, the width of regions 2 and 8 may not be an exact multiple of the width
134 of the corresponding regions in the source image. Similarly, the height of regions 4 and 6
135 may not be an exact multiple of the height of the corresponding regions. It can be useful
136 to use \l{BorderImage::horizontalTileMode}{BorderImage.Round} instead of
137 \l{BorderImage::horizontalTileMode}{BorderImage.Repeat} in cases like these.
139 The \l{declarative/imageelements/borderimage}{BorderImage example} shows how a BorderImage
140 can be used to simulate a shadow effect on a rectangular item.
142 \section1 Quality and Performance
144 By default, any scaled regions of the image are rendered without smoothing to improve
145 rendering speed. Setting the \l smooth property improves rendering quality of scaled
146 regions, but may slow down rendering.
148 The source image may not be loaded instantaneously, depending on its original location.
149 Loading progress can be monitored with the \l progress property.
151 \sa Image, AnimatedImage
155 \qmlproperty bool QtQuick2::BorderImage::asynchronous
157 Specifies that images on the local filesystem should be loaded
158 asynchronously in a separate thread. The default value is
159 false, causing the user interface thread to block while the
160 image is loaded. Setting \a asynchronous to true is useful where
161 maintaining a responsive user interface is more desirable
162 than having images immediately visible.
164 Note that this property is only valid for images read from the
165 local filesystem. Images loaded via a network resource (e.g. HTTP)
166 are always loaded asynchronously.
168 QQuickBorderImage::QQuickBorderImage(QQuickItem *parent)
169 : QQuickImageBase(*(new QQuickBorderImagePrivate), parent)
173 QQuickBorderImage::~QQuickBorderImage()
175 Q_D(QQuickBorderImage);
177 d->sciReply->deleteLater();
181 \qmlproperty enumeration QtQuick2::BorderImage::status
183 This property describes the status of image loading. It can be one of:
186 \li BorderImage.Null - no image has been set
187 \li BorderImage.Ready - the image has been loaded
188 \li BorderImage.Loading - the image is currently being loaded
189 \li BorderImage.Error - an error occurred while loading the image
196 \qmlproperty real QtQuick2::BorderImage::progress
198 This property holds the progress of image loading, from 0.0 (nothing loaded)
205 \qmlproperty bool QtQuick2::BorderImage::smooth
207 Set this property if you want the image to be smoothly filtered when scaled or
208 transformed. Smooth filtering gives better visual quality, but is slower. If
209 the image is displayed at its natural size, this property has no visual or
212 By default, this property is set to false.
214 \note Generally scaling artifacts are only visible if the image is stationary on
215 the screen. A common pattern when animating an image is to disable smooth
216 filtering at the beginning of the animation and enable it at the conclusion.
220 \qmlproperty bool QtQuick2::BorderImage::cache
222 Specifies whether the image should be cached. The default value is
223 true. Setting \a cache to false is useful when dealing with large images,
224 to make sure that they aren't cached at the expense of small 'ui element' images.
228 \qmlproperty bool QtQuick2::BorderImage::mirror
230 This property holds whether the image should be horizontally inverted
231 (effectively displaying a mirrored image).
233 The default value is false.
237 \qmlproperty url QtQuick2::BorderImage::source
239 This property holds the URL that refers to the source image.
241 BorderImage can handle any image format supported by Qt, loaded from any
242 URL scheme supported by Qt.
244 This property can also be used to refer to .sci files, which are
245 written in a QML-specific, text-based format that specifies the
246 borders, the image file and the tile rules for a given border image.
248 The following .sci file sets the borders to 10 on each side for the
249 image \c picture.png:
256 source: "picture.png"
259 The URL may be absolute, or relative to the URL of the component.
261 \sa QQuickImageProvider
265 \qmlproperty QSize QtQuick2::BorderImage::sourceSize
267 This property holds the actual width and height of the loaded image.
269 In BorderImage, this property is read-only.
271 \sa Image::sourceSize
273 void QQuickBorderImage::setSource(const QUrl &url)
275 Q_D(QQuickBorderImage);
281 d->sciReply->deleteLater();
287 emit sourceChanged(d->url);
289 if (isComponentComplete())
293 void QQuickBorderImage::load()
295 Q_D(QQuickBorderImage);
297 if (d->url.isEmpty()) {
300 setImplicitSize(0, 0);
301 emit statusChanged(d->status);
302 if (d->progress != 0.0) {
304 emit progressChanged(d->progress);
306 if (sourceSize() != d->oldSourceSize) {
307 d->oldSourceSize = sourceSize();
308 emit sourceSizeChanged();
313 if (d->url.path().endsWith(QLatin1String("sci"))) {
314 QString lf = QQmlFile::urlToLocalFileOrQrc(d->url);
317 file.open(QIODevice::ReadOnly);
318 setGridScaledImage(QQuickGridScaledImage(&file));
321 if (d->progress != 0.0) {
323 emit progressChanged(d->progress);
326 QNetworkRequest req(d->url);
327 d->sciReply = qmlEngine(this)->networkAccessManager()->get(req);
328 qmlobject_connect(d->sciReply, QNetworkReply, SIGNAL(finished()),
329 this, QQuickBorderImage, SLOT(sciRequestFinished()))
332 QQuickPixmap::Options options;
334 options |= QQuickPixmap::Asynchronous;
336 options |= QQuickPixmap::Cache;
338 d->pix.load(qmlEngine(this), d->url, options);
340 if (d->pix.isLoading()) {
341 if (d->progress != 0.0) {
343 emit progressChanged(d->progress);
346 d->pix.connectFinished(this, SLOT(requestFinished()));
347 d->pix.connectDownloadProgress(this, SLOT(requestProgress(qint64,qint64)));
355 emit statusChanged(d->status);
359 \qmlproperty int QtQuick2::BorderImage::border.left
360 \qmlproperty int QtQuick2::BorderImage::border.right
361 \qmlproperty int QtQuick2::BorderImage::border.top
362 \qmlproperty int QtQuick2::BorderImage::border.bottom
364 The 4 border lines (2 horizontal and 2 vertical) break the image into 9 sections,
367 \image declarative-scalegrid.png
369 Each border line (left, right, top, and bottom) specifies an offset in pixels
370 from the respective edge of the source image. By default, each border line has
373 For example, the following definition sets the bottom line 10 pixels up from
374 the bottom of the image:
383 The border lines can also be specified using a
384 \l {BorderImage::source}{.sci file}.
387 QQuickScaleGrid *QQuickBorderImage::border()
389 Q_D(QQuickBorderImage);
390 return d->getScaleGrid();
394 \qmlproperty enumeration QtQuick2::BorderImage::horizontalTileMode
395 \qmlproperty enumeration QtQuick2::BorderImage::verticalTileMode
397 This property describes how to repeat or stretch the middle parts of the border image.
400 \li BorderImage.Stretch - Scales the image to fit to the available area.
401 \li BorderImage.Repeat - Tile the image until there is no more space. May crop the last image.
402 \li BorderImage.Round - Like Repeat, but scales the images down to ensure that the last image is not cropped.
405 The default tile mode for each property is BorderImage.Stretch.
407 QQuickBorderImage::TileMode QQuickBorderImage::horizontalTileMode() const
409 Q_D(const QQuickBorderImage);
410 return d->horizontalTileMode;
413 void QQuickBorderImage::setHorizontalTileMode(TileMode t)
415 Q_D(QQuickBorderImage);
416 if (t != d->horizontalTileMode) {
417 d->horizontalTileMode = t;
418 emit horizontalTileModeChanged();
423 QQuickBorderImage::TileMode QQuickBorderImage::verticalTileMode() const
425 Q_D(const QQuickBorderImage);
426 return d->verticalTileMode;
429 void QQuickBorderImage::setVerticalTileMode(TileMode t)
431 Q_D(QQuickBorderImage);
432 if (t != d->verticalTileMode) {
433 d->verticalTileMode = t;
434 emit verticalTileModeChanged();
439 void QQuickBorderImage::setGridScaledImage(const QQuickGridScaledImage& sci)
441 Q_D(QQuickBorderImage);
442 if (!sci.isValid()) {
444 emit statusChanged(d->status);
446 QQuickScaleGrid *sg = border();
447 sg->setTop(sci.gridTop());
448 sg->setBottom(sci.gridBottom());
449 sg->setLeft(sci.gridLeft());
450 sg->setRight(sci.gridRight());
451 d->horizontalTileMode = sci.horizontalTileRule();
452 d->verticalTileMode = sci.verticalTileRule();
454 d->sciurl = d->url.resolved(QUrl(sci.pixmapUrl()));
456 QQuickPixmap::Options options;
458 options |= QQuickPixmap::Asynchronous;
460 options |= QQuickPixmap::Cache;
462 d->pix.load(qmlEngine(this), d->sciurl, options);
464 if (d->pix.isLoading()) {
465 if (d->progress != 0.0) {
467 emit progressChanged(d->progress);
469 if (d->status != Loading) {
471 emit statusChanged(d->status);
473 static int thisRequestProgress = -1;
474 static int thisRequestFinished = -1;
475 if (thisRequestProgress == -1) {
476 thisRequestProgress =
477 QQuickBorderImage::staticMetaObject.indexOfSlot("requestProgress(qint64,qint64)");
478 thisRequestFinished =
479 QQuickBorderImage::staticMetaObject.indexOfSlot("requestFinished()");
482 d->pix.connectFinished(this, thisRequestFinished);
483 d->pix.connectDownloadProgress(this, thisRequestProgress);
491 void QQuickBorderImage::requestFinished()
493 Q_D(QQuickBorderImage);
495 QSize impsize = d->pix.implicitSize();
496 if (d->pix.isError()) {
498 qmlInfo(this) << d->pix.error();
499 if (d->progress != 0) {
501 emit progressChanged(d->progress);
505 if (d->progress != 1.0) {
507 emit progressChanged(d->progress);
511 setImplicitSize(impsize.width(), impsize.height());
512 emit statusChanged(d->status);
513 if (sourceSize() != d->oldSourceSize) {
514 d->oldSourceSize = sourceSize();
515 emit sourceSizeChanged();
521 #define BORDERIMAGE_MAX_REDIRECT 16
523 void QQuickBorderImage::sciRequestFinished()
525 Q_D(QQuickBorderImage);
528 if (d->redirectCount < BORDERIMAGE_MAX_REDIRECT) {
529 QVariant redirect = d->sciReply->attribute(QNetworkRequest::RedirectionTargetAttribute);
530 if (redirect.isValid()) {
531 QUrl url = d->sciReply->url().resolved(redirect.toUrl());
538 if (d->sciReply->error() != QNetworkReply::NoError) {
540 d->sciReply->deleteLater();
542 emit statusChanged(d->status);
544 QQuickGridScaledImage sci(d->sciReply);
545 d->sciReply->deleteLater();
547 setGridScaledImage(sci);
551 void QQuickBorderImage::doUpdate()
556 QSGNode *QQuickBorderImage::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
558 Q_D(QQuickBorderImage);
560 QSGTexture *texture = d->sceneGraphContext()->textureForFactory(d->pix.textureFactory(), window());
562 if (!texture || width() <= 0 || height() <= 0) {
567 QSGImageNode *node = static_cast<QSGImageNode *>(oldNode);
570 node = d->sceneGraphContext()->createImageNode();
572 node->setTexture(texture);
574 // Don't implicitly create the scalegrid in the rendering thread...
575 QRectF innerSourceRect(0, 0, 1, 1);
576 QRectF targetRect(0, 0, width(), height());
577 QRectF innerTargetRect = targetRect;
579 const QQuickScaleGrid *border = d->getScaleGrid();
580 innerSourceRect = QRectF(border->left() / qreal(d->pix.width()),
581 border->top() / qreal(d->pix.height()),
582 qMax<qreal>(0, d->pix.width() - border->right() - border->left()) / d->pix.width(),
583 qMax<qreal>(0, d->pix.height() - border->bottom() - border->top()) / d->pix.height());
584 innerTargetRect = QRectF(border->left(),
586 qMax<qreal>(0, width() - border->right() - border->left()),
587 qMax<qreal>(0, height() - border->bottom() - border->top()));
591 if (innerSourceRect.width() != 0) {
592 switch (d->horizontalTileMode) {
593 case QQuickBorderImage::Repeat:
594 hTiles = innerTargetRect.width() / qreal(innerSourceRect.width() * d->pix.width());
596 case QQuickBorderImage::Round:
597 hTiles = qCeil(innerTargetRect.width() / qreal(innerSourceRect.width() * d->pix.width()));
603 if (innerSourceRect.height() != 0) {
604 switch (d->verticalTileMode) {
605 case QQuickBorderImage::Repeat:
606 vTiles = innerTargetRect.height() / qreal(innerSourceRect.height() * d->pix.height());
608 case QQuickBorderImage::Round:
609 vTiles = qCeil(innerTargetRect.height() / qreal(innerSourceRect.height() * d->pix.height()));
616 node->setTargetRect(targetRect);
617 node->setInnerSourceRect(innerSourceRect);
618 node->setInnerTargetRect(innerTargetRect);
619 node->setSubSourceRect(QRectF(0, 0, hTiles, vTiles));
620 node->setMirror(d->mirror);
622 node->setFiltering(d->smooth ? QSGTexture::Linear : QSGTexture::Nearest);
623 if (innerSourceRect == QRectF(0, 0, 1, 1) && (vTiles > 1 || hTiles > 1)) {
624 node->setHorizontalWrapMode(QSGTexture::Repeat);
625 node->setVerticalWrapMode(QSGTexture::Repeat);
627 node->setHorizontalWrapMode(QSGTexture::ClampToEdge);
628 node->setVerticalWrapMode(QSGTexture::ClampToEdge);
630 node->setAntialiasing(d->antialiasing);
636 void QQuickBorderImage::pixmapChange()
638 Q_D(QQuickBorderImage);
640 d->pixmapChanged = true;
642 // When the pixmap changes, such as being deleted, we need to update the textures