一、前言
進入智能手機時代以來,各種各樣的APP大行其道,手機上面的APP有很多流行的元素,開關按鈕個人非常喜歡,手機QQ、360衛士、金山毒霸等,都有很多開關控制一些操作,在WINFORM項目上,如果將CheckBox也改為開關按鈕,估計也會為項目增添不少新鮮感。
沿襲之前的做法,本人還是喜歡直接PS好圖片后,用drawimage方法將圖片繪制到用戶控件上,啟用雙緩沖和背景透明,有些人說PS一張精美的圖片也不是很容易,需要專業的,這里提供一個好方法,讓你也可以獲取到這些圖片,其實大部分的APP都可以用解壓軟件打開,拓展名改為.zip即可,解壓出來一般里面都含有絕大部分的圖片,發現絕大部分的APP都喜歡用圖片作為背景來展示一些效果,而不是原原本本的用代碼一點點繪制。騰訊就是騰訊啊,大公司!人家的美工MM設計的圖片那真的沒得話說,絕對一流,手機QQ每次升級一個版本,都會下過來將里面的精美圖片圖標之類的提取出來,以便項目使用,這不會算是盜版吧!
二、代碼思路
ImageSwitch::ImageSwitch(QWidget *parent) : QWidget(parent)
{
isChecked = false;
buttonStyle = ButtonStyle_2;
imgOffFile = ":/image/btncheckoff2.png";
imgOnFile = ":/image/btncheckon2.png";
imgFile = imgOffFile;
}
void ImageSwitch::mousePressEvent(QMouseEvent *)
{
imgFile = isChecked ? imgOffFile : imgOnFile;
isChecked = !isChecked;
this->update();
}
void ImageSwitch::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHints(QPainter::SmoothPixmapTransform);
QImage img(imgFile);
img = img.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
//按照比例自動居中繪制
int pixX = rect().center().x() - img.width() / 2;
int pixY = rect().center().y() - img.height() / 2;
QPoint point(pixX, pixY);
painter.drawImage(point, img);
}
bool ImageSwitch::getChecked() const
{
return isChecked;
}
ImageSwitch::ButtonStyle ImageSwitch::getButtonStyle() const
{
return this->buttonStyle;
}
QSize ImageSwitch::sizeHint() const
{
return QSize(87, 28);
}
QSize ImageSwitch::minimumSizeHint() const
{
return QSize(87, 28);
}
void ImageSwitch::setChecked(bool isChecked)
{
if (this->isChecked != isChecked) {
this->isChecked = isChecked;
imgFile = isChecked ? imgOnFile : imgOffFile;
this->update();
}
}
void ImageSwitch::setButtonStyle(const ImageSwitch::ButtonStyle &buttonStyle)
{
if (this->buttonStyle != buttonStyle) {
this->buttonStyle = buttonStyle;
if (buttonStyle == ButtonStyle_1) {
imgOffFile = ":/image/btncheckoff1.png";
imgOnFile = ":/image/btncheckon1.png";
this->resize(87, 28);
} else if (buttonStyle == ButtonStyle_2) {
imgOffFile = ":/image/btncheckoff2.png";
imgOnFile = ":/image/btncheckon2.png";
this->resize(87, 28);
} else if (buttonStyle == ButtonStyle_3) {
imgOffFile = ":/image/btncheckoff3.png";
imgOnFile = ":/image/btncheckon3.png";
this->resize(96, 38);
}
imgFile = isChecked ? imgOnFile : imgOffFile;
setChecked(isChecked);
this->update();
updateGeometry();
}
}
三、效果圖
四、開源主頁
以上作品完整源碼下載都在開源主頁,會持續不斷更新作品數量和質量,歡迎各位關注。