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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| #include<QtGui> #include "iconeditor.h" IconEditor::IconEditor(QWidget *parent) : QWidget(parent) { setAttribute(Qt::WA_StaticContents); setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); curColor=Qt::black; zoom=8; image=QImage(16,16,QImage::Format_ARGB32); image.fill(qRgba(0,0,0,0)); }
IconEditor::~IconEditor() { } void IconEditor::setPenColor(const QColor &newColor) { curColor=newColor; } QColor IconEditor::penColor() { return curColor; } void IconEditor::setZoomFactor(int newZoom) { if(newZoom<1) newZoom=1; if(newZoom!=zoom){ zoom=newZoom; this->update(); this->updateGeometry(); } } int IconEditor::zoomFactor() const { return zoom; } void IconEditor::setIconImage(const QImage &newImage) { if(newImage!=image){ image=newImage.convertToFormat(QImage::Format_ARGB32); this->update(); this->updateGeometry(); } } QImage IconEditor::iconImage() const { return image; } QSize IconEditor::sizeHint() const { QSize size=zoom*image.size(); if(zoom>=3) size+=QSize(1,1); return size; }
void IconEditor::paintEvent(QPaintEvent *event) { QPainter painter(this); if(zoom>=3){ painter.setPen(palette().foreground().color()); for(int i=0;i<=image.height();++i) painter.drawLine(zoom*i,0,zoom*image.width(),zoom*i); for(int j=0;j<image.width();++j) painter.drawLine(0,zoom*j,zoom*image.width(),zoom*j); } for(int i=0;i<image.width();++i){ for(int j=0;j<image.height();++j){ QRect rect=pixelRect(i,j); if(!event->region().intersect(rect).isEmpty()){ QColor color=QColor::fromRgba(image.pixel(i,j)); if(color.alpha()<255) painter.fillRect(rect,Qt::white); painter.fillRect(rect,color); } } } } QRect IconEditor::pixelRect(int i,int j) const { if(zoom>=3){ return QRect(zoom*i+1,zoom*j+1,zoom-1,zoom-1); }else{ return QRect(zoom*i,zoom*j,zoom,zoom); } } void IconEditor::mousePressEvent(QMouseEvent *event) { if(event->button()==Qt::LeftButton){ setImagePixel(event->pos(),true); }else if(event->button()==Qt::RightButton){ setImagePixel(event->pos(),false); } } void IconEditor::mouseMoveEvent(QMouseEvent *event) { if(event->buttons()& Qt::LeftButton){ setImagePixel(event->pos(),true); }else if(event->buttons()& Qt::RightButton){ setImagePixel(event->pos(),false); } } void IconEditor::setImagePixel(const QPoint &pos,bool opaque) { int i=pos.x()/zoom; int j=pos.y()/zoom; if(image.rect().contains(i,j)){ if(opaque){ image.setPixel(i,j,penColor().rgba()); }else{ image.setPixel(i,j,qRgba(0,0,0,0)); } } update(pixelRect(i,j)); }
|