一、前言
現在這個時代,智能手機不要太流行,滿大街都是,甚至連爺爺奶奶級別的人都會用智能手機,本次要寫的控件就是智能手機中的電池電量表示控件,采用純painter繪制,其實也可以采用貼圖,我估計大部分手機上的都是采用貼圖的形式,貼圖有個好處就是程序員不用操心,drawimage即可,速度非常快。
至於本控件沒有任何技術難點,就是自動計算當前設置的電量,根據寬度的比例划分100個等分,每個等分占用多少個像素,然后電量*該比例就是要繪制的電量的區域,可以設置報警電量,低於該變量整個電池電量區域紅色顯示。
主要功能:
- 可設置開關按鈕的樣式 圓角矩形/內圓形/外圓形
- 可設置選中和未選中時的背景顏色
- 可設置選中和未選中時的滑塊顏色
- 可設置顯示的文本
- 可設置滑塊離背景的間隔
- 可設置圓角角度
- 可設置是否顯示動畫過渡效果
二、代碼思路
void Battery::paintEvent(QPaintEvent *)
{
//繪制准備工作,啟用反鋸齒
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
//繪制邊框
drawBorder(&painter);
//繪制背景
drawBg(&painter);
//繪制頭部
drawHead(&painter);
}
void Battery::drawBorder(QPainter *painter)
{
painter->save();
double headWidth = width() / 10;
double batteryWidth = width() - headWidth;
//繪制電池邊框
QPointF topLeft(5, 5);
QPointF bottomRight(batteryWidth, height() - 5);
batteryRect = QRectF(topLeft, bottomRight);
painter->setPen(QPen(borderColorStart, 5));
painter->setBrush(Qt::NoBrush);
painter->drawRoundedRect(batteryRect, borderRadius, borderRadius);
painter->restore();
}
void Battery::drawBg(QPainter *painter)
{
painter->save();
QLinearGradient batteryGradient(QPointF(0, 0), QPointF(0, height()));
if (currentValue <= alarmValue) {
batteryGradient.setColorAt(0.0, alarmColorStart);
batteryGradient.setColorAt(1.0, alarmColorEnd);
} else {
batteryGradient.setColorAt(0.0, normalColorStart);
batteryGradient.setColorAt(1.0, normalColorEnd);
}
int margin = qMin(width(), height()) / 20;
double unit = (batteryRect.width() - (margin * 2)) / 100;
double width = currentValue * unit;
QPointF topLeft(batteryRect.topLeft().x() + margin, batteryRect.topLeft().y() + margin);
QPointF bottomRight(width + margin + 5, batteryRect.bottomRight().y() - margin);
QRectF rect(topLeft, bottomRight);
painter->setPen(Qt::NoPen);
painter->setBrush(batteryGradient);
painter->drawRoundedRect(rect, bgRadius, bgRadius);
painter->restore();
}
void Battery::drawHead(QPainter *painter)
{
painter->save();
QPointF headRectTopLeft(batteryRect.topRight().x(), height() / 3);
QPointF headRectBottomRight(width(), height() - height() / 3);
QRectF headRect(headRectTopLeft, headRectBottomRight);
QLinearGradient headRectGradient(headRect.topLeft(), headRect.bottomLeft());
headRectGradient.setColorAt(0.0, borderColorStart);
headRectGradient.setColorAt(1.0, borderColorEnd);
painter->setPen(Qt::NoPen);
painter->setBrush(headRectGradient);
painter->drawRoundedRect(headRect, headRadius, headRadius);
painter->restore();
}
三、效果圖
四、開源主頁
以上作品完整源碼下載都在開源主頁,會持續不斷更新作品數量和質量,歡迎各位關注。