Parses color from string, will probably be moved to a class like CSSColor This implements the most of the W3 specifications found at https://www.w3.org/TR/SVG11/types.html#DataTypeColor It also extends the specifications in a few minor ways This includes more flexible whitespace and some CSS3 features (hsl)
| 1345 | // It also extends the specifications in a few minor ways |
| 1346 | // This includes more flexible whitespace and some CSS3 features (hsl) |
| 1347 | QColor parseColor(QString s) |
| 1348 | { |
| 1349 | // Remove excess whitespace |
| 1350 | s = s.trimmed(); |
| 1351 | if(s.startsWith("rgba") && s.endsWith(")") && s.contains("(")) |
| 1352 | { |
| 1353 | // Remove rgba() |
| 1354 | s.remove(0, 4).chop(1); |
| 1355 | s = s.trimmed().remove(0, 1); |
| 1356 | |
| 1357 | // Split into elements with comma separating them |
| 1358 | QStringList sSplit = s.split(','); |
| 1359 | |
| 1360 | // If it doesn't have exactly four elements, return an invalid color |
| 1361 | if(sSplit.size() != 4) |
| 1362 | { |
| 1363 | return QColor(); |
| 1364 | } |
| 1365 | |
| 1366 | int colors[3]; |
| 1367 | |
| 1368 | // Handle rgb channels |
| 1369 | for(int i = 0; i < 3; i++) |
| 1370 | { |
| 1371 | QString element(sSplit[i]); |
| 1372 | |
| 1373 | // More trimming |
| 1374 | element = element.trimmed(); |
| 1375 | |
| 1376 | // Determine if it is *% or * format |
| 1377 | if(element.endsWith("%")) |
| 1378 | { |
| 1379 | // Remove % sign |
| 1380 | element.chop(1); |
| 1381 | |
| 1382 | colors[i] = qRound(qBound(0.0, element.toDouble(), 100.0) * 2.55); |
| 1383 | } |
| 1384 | else |
| 1385 | { |
| 1386 | colors[i] = qBound(0, qRound(element.toDouble()), 255); |
| 1387 | } |
| 1388 | } |
| 1389 | // Alpha channel is a double from 0.0 to 1.0 inclusive |
| 1390 | double alpha = qBound(0.0, sSplit[3].toDouble(), 1.0); |
| 1391 | |
| 1392 | // Return result |
| 1393 | QColor color = QColor(colors[0], colors[1], colors[2]); |
| 1394 | color.setAlphaF(alpha); |
| 1395 | return color; |
| 1396 | } |
| 1397 | else if(s.startsWith("rgb") && s.endsWith(")") && s.contains("(")) |
| 1398 | { |
| 1399 | // Remove rgb() |
| 1400 | s.remove(0, 3).chop(1); |
| 1401 | s = s.trimmed().remove(0, 1); |
| 1402 | |
| 1403 | // Split into elements with comma separating them |
| 1404 | QStringList sSplit = s.split(','); |