导入 XuXuCheck 工程(iOS 干化学尿液试纸分析 App)

从桌面工程复制而来,作为本仓库的 Xuxucheck/ 子目录。

为控制仓库体积做了两处删减:
- 移除 Frameworks/opencv2.xcframework 下的两个 visionOS 切片
  (xros-arm64、xros-arm64-simulator,合计约 106 MB),并同步删掉该
  xcframework 内 Info.plist 里对应的两条 AvailableLibraries 记录,
  只保留 ios-arm64 与 ios-arm64_x86_64-simulator。
- 移除全部 .DS_Store 与 xcuserdata/。

已用 xcodebuild 从本目录完整编译验证:BUILD SUCCEEDED,
ProcessXCFramework 以 --platform ios 成功选中框架,产物含 3699 个 cv:: 符号
(OpenCV 确实链入),嵌入 framework 3 个,与移除无用 pod 之后的状态一致。

仓库约 206 MB,其中 OpenCV 203 MB、其余源码与依赖约 3 MB。
This commit is contained in:
2026-09-23 14:17:31 +08:00
commit d6aeede2bc
901 changed files with 327267 additions and 0 deletions
@@ -0,0 +1,38 @@
{
"colors" : [
{
"color" : {
"color-space" : "display-p3",
"components" : {
"alpha" : "1.000",
"blue" : "0xD5",
"green" : "0x34",
"red" : "0x62"
}
},
"idiom" : "universal"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"color-space" : "display-p3",
"components" : {
"alpha" : "1.000",
"blue" : "0xFF",
"green" : "0x9E",
"red" : "0x5E"
}
},
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,38 @@
{
"images" : [
{
"filename" : "Frame_2799@3x.png",
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"filename" : "Frame_2799@3x 1.png",
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "tinted"
}
],
"filename" : "Frame_2799@3x 2.png",
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "Avatar Default.jpg",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "Background 1.jpg",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "Background 2.jpg",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "Background 4.jpg",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "Background 5.jpg",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "Background 7.jpg",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,217 @@
%PDF-1.7
1 0 obj
<< /Length 2 0 R
/FunctionType 4
/Domain [ 0.000000 1.000000 ]
/Range [ 0.000000 1.000000 0.000000 1.000000 0.000000 1.000000 ]
>>
stream
{ 0.680000 exch 0.000000 exch 1.000000 exch dup 0.000000 gt { exch pop exch pop exch pop dup 0.000000 sub -0.617441 mul 0.680000 add exch dup 0.000000 sub 0.346745 mul 0.000000 add exch dup 0.000000 sub -0.117162 mul 1.000000 add exch } if dup 0.497884 gt { exch pop exch pop exch pop dup 0.497884 sub 1.249540 mul 0.372586 add exch dup 0.497884 sub 0.270245 mul 0.172639 add exch dup 0.497884 sub -0.104225 mul 0.941667 add exch } if dup 1.000000 gt { exch pop exch pop exch pop 1.000000 exch 0.308333 exch 0.889333 exch } if pop }
endstream
endobj
2 0 obj
533
endobj
3 0 obj
<< /Length 4 0 R
/FunctionType 4
/Domain [ 0.000000 1.000000 ]
/Range [ 0.000000 1.000000 0.000000 1.000000 0.000000 1.000000 ]
>>
stream
{ 0.354046 exch 0.111250 exch 0.741667 exch dup 0.000000 gt { exch pop exch pop exch pop dup 0.000000 sub -0.185418 mul 0.354046 add exch dup 0.000000 sub -0.032819 mul 0.111250 add exch dup 0.000000 sub -0.200490 mul 0.741667 add exch } if dup 1.000000 gt { exch pop exch pop exch pop 0.168627 exch 0.078431 exch 0.541176 exch } if pop }
endstream
endobj
4 0 obj
339
endobj
5 0 obj
<< /BBox [ 0.000000 0.000000 738.000000 504.000000 ]
/Resources << /ExtGState << /E1 << /ca 0.800000 >> >>
/Pattern << /P2 << /Matrix [ -89.297676 541.385132 541.385132 89.297676 -481.977722 -133.584229 ]
/Shading << /Coords [ 0.000000 0.000000 1.000000 0.000000 ]
/Extend [ true true ]
/Domain [ 0.000000 1.000000 ]
/ShadingType 2
/ColorSpace /DeviceRGB
/Function 1 0 R
>>
/PatternType 2
/Type /Pattern
>>
/P1 << /Matrix [ 298.970886 -350.692474 350.692474 298.970886 -285.305023 71.329773 ]
/Shading << /Coords [ 0.000000 0.000000 1.000000 0.000000 ]
/Extend [ true true ]
/Domain [ 0.000000 1.000000 ]
/ShadingType 2
/ColorSpace /DeviceRGB
/Function 3 0 R
>>
/PatternType 2
/Type /Pattern
>>
>>
>>
/Subtype /Form
/Length 6 0 R
/Group << /Type /Group
/S /Transparency
>>
/Type /XObject
>>
stream
/DeviceRGB CS
/DeviceRGB cs
q
1.000000 0.000000 -0.000000 1.000000 0.000061 -44.392426 cm
/Pattern cs
/P1 scn
269.428467 138.087189 m
59.709106 37.050446 -66.856354 274.893402 37.016521 409.180908 c
81.218369 466.325256 141.662384 528.442871 233.870117 464.037445 c
309.190613 411.427429 347.637177 484.222870 411.657196 472.823273 c
466.548828 463.049133 518.117920 484.894348 580.558960 451.957031 c
643.000000 419.019714 735.000000 367.392426 707.000000 273.392426 c
679.000000 179.392426 680.257019 126.020905 587.459961 102.115662 c
476.617310 73.561737 422.856384 221.272125 269.428467 138.087189 c
h
f
n
Q
q
/E1 gs
1.000000 0.000000 -0.000000 -1.000000 52.000000 663.580322 cm
/Pattern cs
/P2 scn
419.097107 207.780243 m
126.230804 38.736938 -94.074966 361.207092 40.412846 546.306396 c
128.815689 667.977661 229.274109 701.694885 348.658661 612.919678 c
446.178711 540.403015 464.187622 638.877441 563.593811 630.728882 c
663.000000 622.580261 743.000000 382.580261 630.000000 330.580261 c
517.000000 278.580261 574.000000 297.190674 419.097107 207.780243 c
h
f
n
Q
endstream
endobj
6 0 obj
1074
endobj
7 0 obj
<< /BBox [ 0.000000 0.000000 738.000000 504.000000 ]
/Resources << >>
/Subtype /Form
/Length 8 0 R
/Group << /Type /Group
/S /Transparency
>>
/Type /XObject
>>
stream
/DeviceRGB CS
/DeviceRGB cs
q
1.000000 0.000000 -0.000000 1.000000 0.000000 0.000000 cm
0.000000 0.000000 0.000000 scn
0.000000 504.000000 m
738.000000 504.000000 l
738.000000 0.000000 l
0.000000 0.000000 l
0.000000 504.000000 l
h
f
n
Q
endstream
endobj
8 0 obj
237
endobj
9 0 obj
<< /XObject << /X1 5 0 R >>
/ExtGState << /E1 << /SMask << /Type /Mask
/G 7 0 R
/S /Alpha
>>
/Type /ExtGState
>> >>
>>
endobj
10 0 obj
<< /Length 11 0 R >>
stream
/DeviceRGB CS
/DeviceRGB cs
q
/E1 gs
/X1 Do
Q
endstream
endobj
11 0 obj
46
endobj
12 0 obj
<< /Annots []
/Type /Page
/MediaBox [ 0.000000 0.000000 738.000000 504.000000 ]
/Resources 9 0 R
/Contents 10 0 R
/Parent 13 0 R
>>
endobj
13 0 obj
<< /Kids [ 12 0 R ]
/Count 1
/Type /Pages
>>
endobj
14 0 obj
<< /Type /Catalog
/Pages 13 0 R
>>
endobj
xref
0 15
0000000000 65535 f
0000000010 00000 n
0000000727 00000 n
0000000749 00000 n
0000001272 00000 n
0000001294 00000 n
0000004235 00000 n
0000004258 00000 n
0000004745 00000 n
0000004767 00000 n
0000005065 00000 n
0000005169 00000 n
0000005191 00000 n
0000005369 00000 n
0000005445 00000 n
trailer
<< /ID [ (some) (id) ]
/Root 14 0 R
/Size 15
>>
startxref
5506
%%EOF
@@ -0,0 +1,217 @@
%PDF-1.7
1 0 obj
<< /Length 2 0 R
/FunctionType 4
/Domain [ 0.000000 1.000000 ]
/Range [ 0.000000 1.000000 0.000000 1.000000 0.000000 1.000000 ]
>>
stream
{ 0.294118 exch 0.721569 exch 0.976471 exch dup 0.000000 gt { exch pop exch pop exch pop dup 0.000000 sub 1.192122 mul 0.294118 add exch dup 0.000000 sub -0.409564 mul 0.721569 add exch dup 0.000000 sub -0.285232 mul 0.976471 add exch } if dup 0.536200 gt { exch pop exch pop exch pop dup 0.536200 sub 0.067642 mul 0.933333 add exch dup 0.536200 sub 0.591871 mul 0.501961 add exch dup 0.536200 sub 0.219838 mul 0.823529 add exch } if dup 1.000000 gt { exch pop exch pop exch pop 0.964706 exch 0.776471 exch 0.925490 exch } if pop }
endstream
endobj
2 0 obj
532
endobj
3 0 obj
<< /Length 4 0 R
/FunctionType 4
/Domain [ 0.000000 1.000000 ]
/Range [ 0.000000 1.000000 0.000000 1.000000 0.000000 1.000000 ]
>>
stream
{ 1.000000 exch 0.000000 exch 0.622857 exch dup 0.000000 gt { exch pop exch pop exch pop dup 0.000000 sub -0.020047 mul 1.000000 add exch dup 0.000000 sub 0.938222 mul 0.000000 add exch dup 0.000000 sub 0.024744 mul 0.622857 add exch } if dup 0.978070 gt { exch pop exch pop exch pop 0.980392 exch 0.917647 exch 0.647059 exch } if pop }
endstream
endobj
4 0 obj
337
endobj
5 0 obj
<< /BBox [ 0.000000 0.000000 738.000000 504.000000 ]
/Resources << /ExtGState << /E1 << /ca 0.500000 >> >>
/Pattern << /P2 << /Matrix [ -89.297676 541.385132 541.385132 89.297676 -481.977722 -133.584259 ]
/Shading << /Coords [ 0.000000 0.000000 1.000000 0.000000 ]
/Extend [ true true ]
/Domain [ 0.000000 1.000000 ]
/ShadingType 2
/ColorSpace /DeviceRGB
/Function 1 0 R
>>
/PatternType 2
/Type /Pattern
>>
/P1 << /Matrix [ 229.685791 -453.308228 809.726501 128.584808 -295.864685 436.983002 ]
/Shading << /Coords [ 0.500000 0.500000 0.000000 0.500000 0.500000 0.500000 ]
/Extend [ true true ]
/Domain [ 0.000000 1.000000 ]
/ShadingType 3
/ColorSpace /DeviceRGB
/Function 3 0 R
>>
/PatternType 2
/Type /Pattern
>>
>>
>>
/Subtype /Form
/Length 6 0 R
/Group << /Type /Group
/S /Transparency
>>
/Type /XObject
>>
stream
/DeviceRGB CS
/DeviceRGB cs
q
1.000000 0.000000 -0.000000 1.000000 0.000061 -44.392426 cm
/Pattern cs
/P1 scn
269.428467 138.087189 m
59.709106 37.050446 -66.856354 274.893402 37.016521 409.180908 c
81.218369 466.325256 141.662384 528.442871 233.870117 464.037445 c
309.190613 411.427429 347.637177 484.222870 411.657196 472.823273 c
466.548828 463.049133 518.117920 484.894348 580.558960 451.957031 c
643.000000 419.019714 735.000000 367.392426 707.000000 273.392426 c
679.000000 179.392426 680.257019 126.020905 587.459961 102.115662 c
476.617310 73.561737 422.856384 221.272125 269.428467 138.087189 c
h
f
n
Q
q
/E1 gs
1.000000 0.000000 -0.000000 -1.000000 52.000000 663.580322 cm
/Pattern cs
/P2 scn
419.097107 207.780243 m
126.230804 38.736938 -94.074966 361.207092 40.412846 546.306396 c
128.815689 667.977661 229.274109 701.694885 348.658661 612.919678 c
446.178711 540.403015 464.187622 638.877441 563.593811 630.728882 c
663.000000 622.580261 743.000000 382.580261 630.000000 330.580261 c
517.000000 278.580261 574.000000 297.190674 419.097107 207.780243 c
h
f
n
Q
endstream
endobj
6 0 obj
1074
endobj
7 0 obj
<< /BBox [ 0.000000 0.000000 738.000000 504.000000 ]
/Resources << >>
/Subtype /Form
/Length 8 0 R
/Group << /Type /Group
/S /Transparency
>>
/Type /XObject
>>
stream
/DeviceRGB CS
/DeviceRGB cs
q
1.000000 0.000000 -0.000000 1.000000 0.000000 0.000000 cm
0.000000 0.000000 0.000000 scn
0.000000 504.000000 m
738.000000 504.000000 l
738.000000 0.000000 l
0.000000 0.000000 l
0.000000 504.000000 l
h
f
n
Q
endstream
endobj
8 0 obj
237
endobj
9 0 obj
<< /XObject << /X1 5 0 R >>
/ExtGState << /E1 << /SMask << /Type /Mask
/G 7 0 R
/S /Alpha
>>
/Type /ExtGState
>> >>
>>
endobj
10 0 obj
<< /Length 11 0 R >>
stream
/DeviceRGB CS
/DeviceRGB cs
q
/E1 gs
/X1 Do
Q
endstream
endobj
11 0 obj
46
endobj
12 0 obj
<< /Annots []
/Type /Page
/MediaBox [ 0.000000 0.000000 738.000000 504.000000 ]
/Resources 9 0 R
/Contents 10 0 R
/Parent 13 0 R
>>
endobj
13 0 obj
<< /Kids [ 12 0 R ]
/Count 1
/Type /Pages
>>
endobj
14 0 obj
<< /Type /Catalog
/Pages 13 0 R
>>
endobj
xref
0 15
0000000000 65535 f
0000000010 00000 n
0000000726 00000 n
0000000748 00000 n
0000001269 00000 n
0000001291 00000 n
0000004251 00000 n
0000004274 00000 n
0000004761 00000 n
0000004783 00000 n
0000005081 00000 n
0000005185 00000 n
0000005207 00000 n
0000005385 00000 n
0000005461 00000 n
trailer
<< /ID [ (some) (id) ]
/Root 14 0 R
/Size 15
>>
startxref
5522
%%EOF
@@ -0,0 +1,52 @@
{
"images" : [
{
"filename" : "Blob 1.pdf",
"idiom" : "universal",
"scale" : "1x"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"filename" : "Blob 1 Dark.pdf",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "home_chart.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "home_intro.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "home_records.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "home_scan.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "home_tutorial.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "ball.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "ball2.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "lay1.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "lay2.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "lay3.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "lay4.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "lay5.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "lay6.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 870 B

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "lay_cycle1.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "lay_logo.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "Logo 1.jpg",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "Logo 2.jpg",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "Logo 3.jpg",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "Logo 4.jpg",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,38 @@
{
"colors" : [
{
"color" : {
"color-space" : "display-p3",
"components" : {
"alpha" : "1.000",
"blue" : "0xFF",
"green" : "0xF6",
"red" : "0xF2"
}
},
"idiom" : "universal"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"color-space" : "display-p3",
"components" : {
"alpha" : "1.000",
"blue" : "0x4B",
"green" : "0x25",
"red" : "0x25"
}
},
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,38 @@
{
"colors" : [
{
"color" : {
"color-space" : "display-p3",
"components" : {
"alpha" : "1.000",
"blue" : "0x7C",
"green" : "0x2A",
"red" : "0x45"
}
},
"idiom" : "universal"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"alpha" : "1.000",
"blue" : "0x00",
"green" : "0x00",
"red" : "0x00"
}
},
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,21 @@
{
"images" : [
{
"filename" : "scanfan.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

@@ -0,0 +1,146 @@
//
// CameraManager.swift
// XuXuCheck
//
// Created by henseycai on 2025/6/25.
//
import AVFoundation
import CoreImage
class CameraManager: NSObject {
private let captureSession = AVCaptureSession()
private var deviceInput: AVCaptureDeviceInput?
private var videoOutput: AVCaptureVideoDataOutput?
private let systemPreferredCamera = AVCaptureDevice.default(for: .video)
private var sessionQueue = DispatchQueue(label: "video.preview.session")
private var addToPreviewStream: ((CGImage) -> Void)?
lazy var previewStream: AsyncStream<CGImage> = {
AsyncStream { continuation in
addToPreviewStream = { cgImage in
continuation.yield(cgImage)
}
}
}()
private var isAuthorized: Bool {
get async {
let status = AVCaptureDevice.authorizationStatus(for: .video)
// Determine if the user previously authorized camera access.
var isAuthorized = status == .authorized
// If the system hasn't determined the user's authorization status,
// explicitly prompt them for approval.
if status == .notDetermined {
isAuthorized = await AVCaptureDevice.requestAccess(for: .video)
}
return isAuthorized
}
}
override init() {
super.init()
Task {
await configureSession()
//await startSession()
}
}
public func StartCapture(){
Task{
await startSession()
}
}
public func StopCapture(){
Task{
await stopSession()
}
}
private func startSession() async {
guard await isAuthorized else { return }
captureSession.startRunning()
}
private func stopSession() async {
guard await isAuthorized else { return }
captureSession.stopRunning()
}
private func configureSession() async {
guard await isAuthorized,
let systemPreferredCamera,
let deviceInput = try? AVCaptureDeviceInput(device: systemPreferredCamera)
else { return }
captureSession.beginConfiguration()
defer {
self.captureSession.commitConfiguration()
}
let videoOutput = AVCaptureVideoDataOutput()
videoOutput.setSampleBufferDelegate(self, queue: sessionQueue)
guard captureSession.canAddInput(deviceInput) else {
return
}
guard captureSession.canAddOutput(videoOutput) else {
return
}
captureSession.addInput(deviceInput)
captureSession.addOutput(videoOutput)
//For a vertical orientation of the camera stream
videoOutput.connection(with: .video)?.videoRotationAngle = 90
}
private func rotate(by angle: CGFloat, from connection: AVCaptureConnection) {
guard connection.isVideoRotationAngleSupported(angle) else { return }
connection.videoRotationAngle = angle
}
}
extension CameraManager: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let currentFrame = sampleBuffer.cgImage else {
print("Can't translate to CGImage")
return
}
addToPreviewStream?(currentFrame)
}
}
extension CMSampleBuffer {
var cgImage: CGImage? {
let pixelBuffer: CVPixelBuffer? = CMSampleBufferGetImageBuffer(self)
guard let imagePixelBuffer = pixelBuffer else { return nil }
return CIImage(cvPixelBuffer: imagePixelBuffer).cgImage
}
}
extension CIImage {
var cgImage: CGImage? {
let ciContext = CIContext()
guard let cgImage = ciContext.createCGImage(self, from: self.extent) else { return nil }
return cgImage
}
}
+230
View File
@@ -0,0 +1,230 @@
//
// CameraView.swift
// XuXuCheck
//
// Created by henseycai on 2025/6/25.
//
import SwiftUI
struct CameraView: View {
// @Binding var image: CGImage?
// @Binding var array3D: [[[Double]]]
@Environment(CameraViewModel.self) private var cameraViewModel
@Environment(\.dismiss) private var dissmiss
//https://cloverlaun.tistory.com/77
//https://stackoverflow.com/questions/59438285/disable-swipe-back-for-a-navigationlink-swiftui/65354662
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@State private var showingNaiveSafariViewFullScreenCover = false
@State var isAnimating = false
//let grayImage = OpenCVWrapper.toGrayscale(uiImage)
var body: some View {
ZStack (alignment: .top){
GeometryReader { geometry in
if let image = cameraViewModel.currentFrame {
let uiImage = UIImage(cgImage: image)
let result = OpenCVWrapper.analysisImage(uiImage)
let wbArr = result.paperWbValue as! [Double]
// let descArr = result.paperTypeDesc as! [Int]
// let wbArr = result.paperWbValue as! [Int]
if(wbArr[3] == 0){
if(cameraViewModel.array3D.count < 16){
let _ = cameraViewModel.array3D.append(result.paperAnalResults as! [[Double]])
// let _ = print(cameraViewModel.array3D.count)
}else{
if(cameraViewModel.isDataSent == false){
let _ = print(cameraViewModel.array3D)
//let _ = cameraViewModel.stopSession()
let _ = cameraViewModel.addRecord(desc: result.paperTypeDesc as! [Int])
}
//following line works just bcs Image come continuously ,so following triggered. thanks God~
// if(cameraViewModel.isSuccess == true){
// let _ = self.presentationMode.wrappedValue.dismiss()
//
// XuXuWebView(currentUrl: cameraViewModel.recordDetailUrl())
// }
}
//let _ = print(wbArr)
// let _ = print(descArr)
}
Image(uiImage: result.srcImg)
.resizable()
.scaledToFit()
.frame(width: geometry.size.width,
height: geometry.size.height)
//.clipped()
/*clipped() This crucial modifier crops any content of the view that extends beyond its defined frame. When combined with .scaledToFill() and .frame(), it effectively "crops" the image to the specified dimensions.*/
Image("scanfan").resizable().frame(width: 60,height: 235)
.offset(x: isAnimating ? geometry.size.width : -50,y:70)
.animation(.easeInOut(duration: 5).repeatForever(autoreverses: false), value: isAnimating)
.onAppear{
isAnimating.toggle()
}
Text("Scan urinal strip in natural light. Put strip on white paper towel.Ensure strip is completely presented in green box.").foregroundStyle(Color.white)
.font(.title2).frame(maxWidth: .infinity, maxHeight:.infinity,alignment: .topLeading)
.padding().background(Color.gray)
.offset(x:0,y:400)
} else {
// ContentUnavailableView("Camera feed interrupted", systemImage: "xmark.circle.fill")
// .frame(width: geometry.size.width,
// height: geometry.size.height)
}
}
.padding(.top,20)
.onChange(of: cameraViewModel.isSuccess){oldState,newState in
if(oldState == false && newState == true){
//https://www.hackingwithswift.com/quick-start/swiftui/how-to-run-some-code-when-state-changes-using-onchange
//https://developer.apple.com/documentation/swiftui/view/onchange(of:perform:)
// showingNaiveSafariViewFullScreenCover = true
// dissmiss()
showingNaiveSafariViewFullScreenCover.toggle()
}
}
.onChange(of: cameraViewModel.isNeedPopErr){oldState,newState in
if(oldState == false && newState == true){
showTopToast.toggle()
}
}
.fullScreenCover(isPresented: $showingNaiveSafariViewFullScreenCover) {
XuXuWebView(currentUrl: cameraViewModel.recordDetailUrl())
}
.present(isPresented: self.$showTopToast, type: .toast, position: .top, duration: 6.0, onTap: {
}, onToastDismiss: {
dissmiss()
}) {
self.createTopToastView()
}
HStack {
Image(systemName: "arrow.backward")
.frame(width: 50, height: 50)
.foregroundColor(.secondary)
.strokeStyle(cornerRadius: 15)
.onTapGesture {
dissmiss()
}
Text("Scanning").font(.headline).frame(maxWidth: .infinity, alignment: .center)
}.padding(.top,50)
}
// .navigationBarTitleDisplayMode(.inline)
// .toolbar{
// ToolbarItem(placement:.principal){
//
//
// Text("Timer").font(.headline)
// }
// }
//
// .navigationBarItems(
// leading: Button(action: {
// dissmiss()
// }, label: {
// Image(systemName: "arrow.backward")
// .foregroundColor(Color(red: 231/255, green: 200/255, blue: 153/255))
// }), trailing: Button(action: {
// // 点击按钮时的操作
// }, label: {
// Text("明细")
// .foregroundColor(Color(red: 231/255, green: 200/255, blue: 153/255))
// }))
}
let topToastColor = Color(hex: "4067CC")
@State var showTopToast = false
func createTopToastView() -> some View {
VStack {
Spacer(minLength: 30)
HStack() {
Image("AppIcon")
.resizable()
.aspectRatio(contentMode: ContentMode.fill)
.frame(width: 50, height: 50)
.cornerRadius(25)
VStack(alignment: .leading, spacing: 2) {
HStack {
Text("Error")
.font(.system(size: 18))
.foregroundColor(.white)
.fontWeight(.bold)
Spacer()
Image(systemName: "info")
.font(.system(size: 12))
.foregroundColor(.white)
}
Text("\(cameraViewModel.xuxuError?.message)" + "!")
.lineLimit(2)
.font(.system(size: 16))
.foregroundColor(.white)
}
}.padding(15)
}
.frame(height: 130)
.background(self.topToastColor)
}
}
#Preview {
CameraView()
// CameraView(image: .constant(nil),array3D: .constant([]))
}
@@ -0,0 +1,92 @@
//
// CameraViewModel.swift
// XuXuCheck
//
// Created by henseycai on 2025/6/25.
//
import Foundation
import CoreImage
@Observable
class CameraViewModel {
var currentFrame: CGImage?
var array3D: [[[Double]]] = []
var arrayPaperDesc: [Int] = [0,0,0,0]
var isSuccess: Bool = false
var isDataSent: Bool = false
var recordId: Int = 0
var recordResultModel: RecordResultModel? = nil
var xuxuError:XuXuRespError? = nil
var isNeedPopErr = false
private let cameraManager = CameraManager()
init() {
Task {
await handleCameraPreviews()
}
}
private func resetData(){
recordId = 0
isSuccess = false
isDataSent = false
isNeedPopErr = false
array3D = []
}
func startSession(){
//init data
resetData()
cameraManager.StartCapture()
}
func stopSession(){
cameraManager.StopCapture()
}
func handleCameraPreviews() async {
for await image in cameraManager.previewStream {
Task { @MainActor in
currentFrame = image
}
}
}
func recordDetailUrl() -> String{
let res = API.webrecordDetailUrl + GetGeneralRequestParams() + "&record_type=0&record_id=\(recordId)"
return res
}
func addRecord(desc: [Int]){
self.isDataSent = true
APIService.instance.addNewRecord(with: desc, with: array3D, completion: {(model,error) in
// debugPrint(desc[0])
// debugPrint(desc[1])
// debugPrint(desc[2])
if let error = error{
debugPrint(error)
self.xuxuError = error
self.isNeedPopErr = true
return
}
self.recordResultModel = model
self.recordId = model?.data?.record_id ?? 0
self.isSuccess = true
})
}
}
+41
View File
@@ -0,0 +1,41 @@
//
// ScanView.swift
// XuXuCheck
//
// Created by henseycai on 2025/6/25.
//
import SwiftUI
struct ScanView: View {
// @State
// private var viewModel = CameraViewModel()
// @Environment(CameraViewModel.self) private var cameraViewModel
@State private var canStartScan = false
@Environment(CameraViewModel.self) private var cameraViewModel
var body: some View {
// CameraView(image: $viewModel.currentFrame,array3D: $viewModel.array3D)
// .ignoresSafeArea()
if(canStartScan){
CameraView()
.onDisappear {
//can this line be called?????????????????
cameraViewModel.stopSession()
}
.ignoresSafeArea()
}else{
TimerCountView(canStartScan: $canStartScan)
.ignoresSafeArea()
}
}
}
#Preview {
ScanView()
}
@@ -0,0 +1,131 @@
//
// TimerCountView.swift
// XuXuCheck
//
// Created by henseycai on 2025/7/25.
//
import SwiftUI
struct TimerCountView: View {
@State var timeRemaining: Int = 60
@State var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
@Binding var canStartScan: Bool
@Environment(\.dismiss) private var dissmiss
@Environment(CameraViewModel.self) private var cameraViewModel
var body: some View {
let bgcolor = Color(hex: 0x2449f1)
let bgcolor2 = Color(hex: 0x1638d9)
VStack{
HStack {
Image(systemName: "arrow.backward")
.frame(width: 50, height: 50)
.foregroundColor(.primary)
.strokeStyle(cornerRadius: 15)
.onTapGesture {
dissmiss()
}
Text("Countdown Timer").font(.headline).frame(maxWidth: .infinity, alignment: .center)
}
ZStack {
// Digit Counter
Text(
"\(timeRemaining)s"
)
.font(.system(size: 56, weight: .bold))
// Circle Counter
Group {
Circle()
.rotation(.degrees(-90))
.stroke(
bgcolor.opacity(0.3),
style: StrokeStyle(lineWidth: 12, dash: [CGFloat.pi / 2, CGFloat.pi * 3.5])
)
Circle()
.trim(
from: 0,
to: (CGFloat(timeRemaining).truncatingRemainder(dividingBy: 60) - 0.25) / 60
)
.rotation(.degrees(-90))
.stroke(
bgcolor2.opacity(0.8),
style: StrokeStyle(lineWidth: 12, dash: [CGFloat.pi / 2, CGFloat.pi * 3.5])
)
}
.frame(width: 240, height: 240)
}.onReceive(timer){ _ in
if timeRemaining > 0 {
// if timeremaining is greater than zero subtract 1
timeRemaining -= 1
}
else
{
//else reset it to 5 if its equal to 0. this will save it from a negative num
timeRemaining = 60
self.timer.upstream.connect().cancel()
cameraViewModel.startSession()
canStartScan = true
//dissmiss()
}
}
Text("Urine chemical reaction needs one minute about. Please put strip on white paper towel.").foregroundStyle(.primary)
.font(.title2).frame(maxWidth: .infinity, alignment: .center)
.offset(x:20,y:100)
///-----------------------------
Spacer()
HStack{
Button(action: {
timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
timeRemaining = 60
}, label: {
Text("Reset Timer")
.frame(width: 120)
.padding()
.foregroundColor(.white)
.background(Color.gray)
.cornerRadius(10)
})
Spacer()
Button(action: {
self.timer.upstream.connect().cancel()
cameraViewModel.startSession()
canStartScan = true
}, label: {
Text("Scan Now")
.frame(width: 120)
.padding()
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(10)
})
}
}.padding(50)
}
}
@@ -0,0 +1,71 @@
//
// BlobView.swift
// XuXuCheck
//
// Created by henseycai on 2025/6/11.
//
import SwiftUI
struct BlobView: View {
@State var appear = false
var body: some View {
TimelineView(.animation) { timeline in
let now = timeline.date.timeIntervalSinceReferenceDate
let angle = Angle.degrees(now.remainder(dividingBy: 3) * 50)
let x = cos(angle.radians)
let angle2 = Angle.degrees(now.remainder(dividingBy: 6) * 10)
let x2 = cos(angle2.radians);
Canvas { context, size in
context.fill(path(in: CGRect(x: 0, y: 0, width: size.width, height: size.height), x: x, x2: x2), with: .linearGradient(Gradient(colors: [.pink,.blue]), startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 390, y: 390)))
}
.frame(width: 400, height: 410)
.rotationEffect(.degrees(appear ? 360 : 30))
}
.onAppear {
withAnimation(.linear(duration: 15).repeatCount(4, autoreverses: true)) {
appear = true
}
}
}
// .foregroundStyle(.linearGradient(colors: [.pink, .blue], startPoint: .topLeading, endPoint: .bottomTrailing))
func path(in rect: CGRect, x: Double, x2: Double) -> Path {
var path = Path()
let width = rect.size.width
let height = rect.size.height
path.move(to: CGPoint(x: 0.9923*width, y: 0.42593*height))
path.addCurve(to: CGPoint(x: 0.6355*width, y: height), control1: CGPoint(x: 0.92554*width*x2, y: 0.77749*height*x2), control2: CGPoint(x: 0.91864*width*x2, y: height))
path.addCurve(to: CGPoint(x: 0.08995*width, y: 0.60171*height), control1: CGPoint(x: 0.35237*width*x, y: height), control2: CGPoint(x: 0.2695*width, y: 0.77304*height))
path.addCurve(to: CGPoint(x: 0.34086*width, y: 0.06324*height*x), control1: CGPoint(x: -0.0896*width, y: 0.43038*height), control2: CGPoint(x: 0.00248*width, y: 0.23012*height*x))
path.addCurve(to: CGPoint(x: 0.9923*width, y: 0.42593*height), control1: CGPoint(x: 0.67924*width, y: -0.10364*height*x), control2: CGPoint(x: 1.05906*width, y: 0.07436*height*x2))
path.closeSubpath()
return path
}
}
struct BlobView_Previews: PreviewProvider {
static var previews: some View {
BlobView()
}
}
struct BlobShape: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
let width = rect.size.width
let height = rect.size.height
path.move(to: CGPoint(x: 0.9923*width, y: 0.42593*height))
path.addCurve(to: CGPoint(x: 0.6355*width, y: height), control1: CGPoint(x: 0.92554*width, y: 0.77749*height), control2: CGPoint(x: 0.91864*width, y: height))
path.addCurve(to: CGPoint(x: 0.08995*width, y: 0.60171*height), control1: CGPoint(x: 0.35237*width, y: height), control2: CGPoint(x: 0.2695*width, y: 0.77304*height))
path.addCurve(to: CGPoint(x: 0.34086*width, y: 0.06324*height), control1: CGPoint(x: -0.0896*width, y: 0.43038*height), control2: CGPoint(x: 0.00248*width, y: 0.23012*height))
path.addCurve(to: CGPoint(x: 0.9923*width, y: 0.42593*height), control1: CGPoint(x: 0.67924*width, y: -0.10364*height), control2: CGPoint(x: 1.05906*width, y: 0.07436*height))
path.closeSubpath()
return path
}
}
@@ -0,0 +1,23 @@
//
// HexagonView.swift
// XuXuCheck
//
// Created by henseycai on 2025/6/11.
//
import SwiftUI
struct HexagonView: View {
var body: some View {
Image(systemName: "hexagon")
.symbolVariant(.fill)
.foregroundColor(.blue)
.font(.system(size: 200))
}
}
struct HexagonView_Previews: PreviewProvider {
static var previews: some View {
HexagonView()
}
}
@@ -0,0 +1,239 @@
//
// ScanView.swift
// XuXuCheck
//
// Created by henseycai on 2025/6/25.
//
import SwiftUI
@preconcurrency
import WebKit
struct WebViewRepresentable: UIViewRepresentable {
var currentUrl: String
@Environment(WebViewModel.self) var webViewModel
// let viewModel: WebViewModel
let webView = WKWebView()
@Environment(LoginStatus.self) var loginStatus
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> WKWebView {
webView.navigationDelegate = context.coordinator
// 让网页从 webView 自己的顶端开始渲染。默认的 .automatic 会在 webView 铺到状态栏
// 下面之后再加一份安全区 inset,内容被二次下推,顶部就多出一条空白带。
// 它同时决定底部:内容区不再被安全区收窄,所以底部也不会自动让出 34pt,
// 滚动内容会一直用到 webView 的物理底边。
// 顶部到底留多少由 XuXuWebView 的 topSafeInset 统一控制;推导见 docs/webview-safe-area.md
webView.scrollView.contentInsetAdjustmentBehavior = .never
if(currentUrl.isEmpty == false){
webViewModel.hasNewCommand = false
webViewModel.url = URL(string:currentUrl)
}
if let url = webViewModel.url {
webView.load(URLRequest(url: url))
}
webViewModel.assignWebView(webView: webView)
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
}
class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
var parent: WebViewRepresentable
var webView: WKWebView {
parent.webView
}
var webViewModel: WebViewModel {
parent.webViewModel
}
init(_ parent: WebViewRepresentable) {
self.parent = parent
super.init()
// Add addScriptMessageHandler in javascript: window.webkit.messageHandlers.MyObserver.postMessage()
webView.configuration.userContentController.add(self, name: "receiveData")
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .linkActivated {
if let url = navigationAction.request.url {
webView.load(URLRequest(url: url))
decisionHandler(.cancel)
return
}
}
decisionHandler(.allow)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
webViewModel.isLoading = true
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webViewModel.isLoading = false
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
webViewModel.isLoading = false
webViewModel.error = error
print("loading error: \(error)")
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
let messageFromWebPage = message.body as! String
let jsonData = messageFromWebPage.data(using: .utf8)!
print(jsonData)
do {
let js2obj = try JSONDecoder().decode(JS2SwiftModel.self, from: jsonData)
webViewModel.jsParameter = js2obj.parameter
webViewModel.jsCommand = js2obj.command
webViewModel.hasNewCommand = true
print(js2obj)
print(webViewModel.jsCommand?.lowercased())
switch webViewModel.jsCommand?.lowercased(){
case "print":
break
case "tel":
break
case "clearcache":
break
case "setdefaultmember":
if let member_data = webViewModel.jsParameter?.member_data {
Storage.shared.member_id = member_data.member_id ?? 0
Storage.shared.member_name = member_data.member_name ?? ""
}
break
case "changeself":
if let dataSelf = webViewModel.jsParameter?.jsSelf {
Storage.shared.userid = dataSelf.user_id ?? 0
Storage.shared.mobile = dataSelf.user_mobile ?? ""
Storage.shared.email = dataSelf.user_email ?? ""
Storage.shared.username = dataSelf.username ?? ""
}
break
case "goback":
break
case "scanpaper":
break
case "logout":
Storage.shared.email = ""
Storage.shared.username = ""
Storage.shared.isLogin = false
Storage.shared.member_id = 0
Storage.shared.mobile = ""
Storage.shared.userid = 0
Storage.shared.usertoken = ""
Storage.shared.member_name = ""
//can do this
parent.loginStatus.isLogin = false
break
case "login":
Storage.shared.email = ""
Storage.shared.username = ""
Storage.shared.isLogin = false
Storage.shared.member_id = 0
Storage.shared.mobile = ""
Storage.shared.userid = 0
Storage.shared.usertoken = ""
Storage.shared.member_name = ""
//can do this
parent.loginStatus.routeToLoginView = true
break
default:
break
}
}catch{
print("error decoding json:\(error)")
}
// if messageFromWebPage == "index" {
// viewModel.backButtonIsEnabled = false
// viewModel.loadFile(name: messageFromWebPage)
// return
// }
// if messageFromWebPage == "goPage" {
// viewModel.backButtonIsEnabled = true
// return
// }
//
// let alertController = UIAlertController(title: "Javascript said:", message: messageFromWebPage, preferredStyle: .alert)
// let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
// print("OK")
// }
// alertController.addAction(okAction)
// guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
// let rootViewController = windowScene.windows.first?.rootViewController else {
// return
// }
// rootViewController.present(alertController, animated: true)
}
/// Callback from javascript: window.webkit.messageHandlers.MyObserver.postMessage(message)
// func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
// let messageFromWebPage = message.body as! String
//
// if messageFromWebPage == "index" {
// viewModel.backButtonIsEnabled = false
// viewModel.loadFile(name: messageFromWebPage)
// return
// }
// if messageFromWebPage == "goPage" {
// viewModel.backButtonIsEnabled = true
// return
// }
//
// let alertController = UIAlertController(title: "Javascript said:", message: messageFromWebPage, preferredStyle: .alert)
// let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
// print("OK")
// }
// alertController.addAction(okAction)
// guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
// let rootViewController = windowScene.windows.first?.rootViewController else {
// return
// }
// rootViewController.present(alertController, animated: true)
// }
}
}
@@ -0,0 +1,203 @@
//
// XuXuWebView.swift
// XuXuCheck
//
// Created by henseycai on 2025/6/25.
//
import Foundation
import SwiftUI
struct XuXuWebView: View {
// @Bindable var webViewModel = WebViewModel()
var currentUrl: String
@Environment(\.dismiss) private var dissmiss
@Environment(LoginStatus.self) var loginStatus
@Environment(WebViewModel.self) var webViewModel
@Environment(Status.self) var status
@State private var showingNaiveSafariViewFullScreenCover = false
@State var imageViewModel = ImagePickerViewModel()
@State var iScanQrPresented = false
@State private var scannedCode: String?
/// 顶部留白高度(pt)。
/// 网页的头部是按"浏览器里已经让开状态栏"来设计的,把 webview 直接铺到物理顶端(y=0)后,
/// 它的标题会顶进灵动岛,左上角的返回键也会落进系统手势区里导致点不到。
/// 这里稍微下移一点点:标题和返回键都能落在灵动岛下方,又不像原来那样露出一大条蓝色空白。
/// 调整手感只需要改这一个数值。
private let topSafeInset: CGFloat = 20
let actions = ["changeText('hello from Swift')", "goBack()"]
static var date: String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter.string(from: Date())
}
var body: some View {
ZStack{
// 网页的底色层:必须铺满四周(含底部)。
// 它就是 webview 后面那层背景,底部漏掉的话,webview 停在安全区上时
// 最下面 34pt 露出的会是 XuXuWebView 外面父视图的白底,在网页浅色背景下面很显眼。
// 键盘那一路单独忽略,是为了键盘弹出时这层底色不被顶起来。
Color(hex: 0x395cff).ignoresSafeArea(.keyboard,edges: .bottom)
.ignoresSafeArea(.container,edges: [.top,.horizontal,.bottom])
VStack {
WebViewRepresentable(currentUrl: currentUrl)
.cornerRadius(1)
.onChange(of: webViewModel.hasNewCommand) {
oldState,
newState in
print(webViewModel.hasNewCommand)
if oldState == false && newState == true {
//https://www.hackingwithswift.com/quick-start/swiftui/how-to-run-some-code-when-state-changes-using-onchange
//https://developer.apple.com/documentation/swiftui/view/onchange(of:perform:)
switch webViewModel.jsCommand?.lowercased() {
case "print":
break
case "tel":
break
case "clearcache":
break
case "setdefaultmember":
break
case "changeself":
break
case "goback":
// print(" go back")
status.showNavDetail = false
// status.showNavDetail.toggle()
dissmiss()
break
case "scancode":
iScanQrPresented.toggle()
break
case "selectphoto":
print("i will select photo")
imageViewModel.choosePhoto()
break
case "selectcamera":
print("i will take photo")
imageViewModel.takePhoto()
break
case "scanpaper":
showingNaiveSafariViewFullScreenCover.toggle()
break
case "logout":
print("logout")
// 网页里退出登录后要退出本页回到 Mine,和 goback 一样属"正常离开",
// 所以这里立刻把导航条恢复;onDisappear 那层是兜底,
// 万一将来又加一条不以 goback/logout 结束的退出路径也不会漏。
status.showNavDetail = false
dissmiss()
break
case "login":
break
default:
break
}
webViewModel.hasNewCommand = false
}
}
.onChange(of: imageViewModel.isPresentingImagePicker){
oldState, newState in
if oldState == true && newState == false {
if let image = imageViewModel.selectedImage {
// webViewModel.callJsImage(imageString: image.jpegBase64)
if let base64 = image.getJpegBase64(){
webViewModel.callJsImage(imageString: base64)
}
//webViewModel.callJsImage(imageString: image.getJpegBase64())
// webViewModel.callJsImage(imageString: convertImageToBase64(image: image))
}
}
}
.fullScreenCover(isPresented: $imageViewModel.isPresentingImagePicker, content: {
ImagePicker(sourceType: imageViewModel.sourceType, completionHandler: imageViewModel.didSelectImage)
})
.fullScreenCover(
isPresented: $showingNaiveSafariViewFullScreenCover
) {
ScanView()
}
.sheet(isPresented: $iScanQrPresented) {
CodeScannerView(codeTypes: [.qr]) { response in
if case let .success(result) = response {
scannedCode = result.string
if let code = scannedCode {
webViewModel.callJsBarcode(named: code)
}
iScanQrPresented = false
}
}
}
}
// 顶部(半通屏):先把内容下移 topSafeInset,再让容器铺到物理顶端。
// 顺序不能反 —— 先忽略安全区再加 .padding,等于给一个已经满屏的视图加外衬距,底部会被挤出容器。
// 这样网页从灵动岛下方开始渲染,上面露出的那一小条就是本页的蓝色底。
// 底部(全通屏):必须一直铺到物理底边。原先这里只忽略 .top,webview 停在底部安全区上,
// 最下面 34pt 没有任何一层去画,露出的是父视图的白底。
// 顶部和底部的现象都是"留白",但成因相反:顶部是让位让多了(要收),底部是压根没铺到(要铺满)。
// 判断依据是这块区域显示的是谁的颜色,详见 docs/webview-safe-area.md
.padding(.top, topSafeInset)
.ignoresSafeArea(.container, edges: [.top, .bottom])
// 底部导航的藏/显示必须成对绑在本视图的生命周期上。
// 注意 showNavDetail 名字是反的:true = 正在看详情页 = 把 TabBar 推出屏幕
// (ContentView 里 `TabBar().offset(y: showNavDetail ? 200 : 0)`)。
// 原先只有 onAppear 这一半,"恢复"是由网页上报 goback 命令顺带做的 ——
// 于是任何不以 goback 结束的退出路径都会把导航条留在屏幕外
// (Mine → 设置 → 退出登录 就是:那个分支只 dismiss,没有恢复)。
.onAppear {
//status.showNavDetail.toggle()
status.showNavDetail = true
}
.onDisappear {
status.showNavDetail = false
}
}
// .frame(maxWidth: .infinity,maxHeight: .infinity)
// .edgesIgnoringSafeArea(.all)
}
}
#Preview {
XuXuWebView(currentUrl: API.webrecordUrl + GetGeneralRequestParams())
}
+71
View File
@@ -0,0 +1,71 @@
//
// ContentView.swift
// XuXuCheck
//
// Created by henseycai on 2025/5/26.
//
import SwiftUI
struct ContentView: View {
@AppStorage("selectedTab") var selectedTab: Tab = .home
@Environment(Status.self) var status: Status
@Bindable var webViewModel = WebViewModel()
@Environment(LoginStatus.self) var loginStatus
var body: some View {
ZStack {
switch selectedTab {
case .home:
HomeView()
case .members:
if(loginStatus.isLogin){
XuXuWebView(currentUrl: API.webMemberListUrl + GetGeneralRequestParams())
}else{
LoginView()
}
case .records:
if(loginStatus.isLogin){
XuXuWebView(currentUrl: API.webrecordUrl + GetGeneralRequestParams())
}else{
LoginView()
}
case .mine:
MineView()
}
TabBar().offset(y: status.showNavDetail ? 200 : 0)
}
.safeAreaInset(edge: .bottom) {
Color.clear.frame(height: 44)
}
}
}
/*
struct ContentView: View {
@State private var image = UIImage(named: "image")!
var body: some View {
VStack {
Image(uiImage: image)
.resizable()
Button("Convert to grayscale") {
let grayImage = OpenCVWrapper.toGrayscale(image)
image = grayImage
}
Button("Apply gaussian blur") {
let blurImage = OpenCVWrapper.gaussianBlur(image, 125)
image = blurImage
}
}
}
}
*/
@@ -0,0 +1,39 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import Foundation
/**
Convenient extension for color array to work as a DynamicGradient.
*/
public extension Array where Element: DynamicColor {
/**
Gradient representation of the array.
*/
var gradient: DynamicGradient {
return DynamicGradient(colors: self)
}
}
@@ -0,0 +1,60 @@
//
// ContrastDisplayContext.swift
// DynamicColorExample
//
// Created by Yannick LORIOT on 26/11/2016.
// Copyright © 2016 Yannick LORIOT. All rights reserved.
//
import Foundation
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
extension DynamicColor {
/**
Used to describe the context of display of 2 colors.
Based on WCAG: https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast
*/
public enum ContrastDisplayContext {
/**
A standard text in a normal context.
*/
case standard
/**
A large text in a normal context.
You can look here for the definition of "large text":
https://www.w3.org/TR/2008/REC-WCAG20-20081211/#larger-scaledef
*/
case standardLargeText
/**
A standard text in an enhanced context.
Enhanced means that you want to be accessible (and AAA compliant in WCAG)
*/
case enhanced
/**
A large text in an enhanced context.
Enhanced means that you want to be accessible (and AAA compliant in WCAG)
You can look here for the definition of "large text":
https://www.w3.org/TR/2008/REC-WCAG20-20081211/#larger-scaledef
*/
case enhancedLargeText
var minimumContrastRatio: CGFloat {
switch self {
case .standard:
return 4.5
case .standardLargeText:
return 3.0
case .enhanced:
return 7.0
case .enhancedLargeText:
return 4.5
}
}
}
}
@@ -0,0 +1,137 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
// MARK: Deriving Colors
public extension DynamicColor {
/**
Creates and returns a color object with the hue rotated along the color wheel by the given amount.
- parameter amount: A float representing the number of degrees as ratio (usually between -360.0 degree and 360.0 degree).
- returns: A DynamicColor object with the hue changed.
*/
final func adjustedHue(amount: CGFloat) -> DynamicColor {
return HSL(color: self).adjustedHue(amount: amount).toDynamicColor()
}
/**
Creates and returns the complement of the color object.
This is identical to adjustedHue(180).
- returns: The complement DynamicColor.
- seealso: adjustedHueColor:
*/
final func complemented() -> DynamicColor {
return adjustedHue(amount: 180.0)
}
/**
Creates and returns a color object with the lightness increased by the given amount.
- parameter amount: CGFloat between 0.0 and 1.0. Default value is 0.2.
- returns: A lighter DynamicColor.
*/
final func lighter(amount: CGFloat = 0.2) -> DynamicColor {
return HSL(color: self).lighter(amount: amount).toDynamicColor()
}
/**
Creates and returns a color object with the lightness decreased by the given amount.
- parameter amount: Float between 0.0 and 1.0. Default value is 0.2.
- returns: A darker DynamicColor.
*/
final func darkened(amount: CGFloat = 0.2) -> DynamicColor {
return HSL(color: self).darkened(amount: amount).toDynamicColor()
}
/**
Creates and returns a color object with the saturation increased by the given amount.
- parameter amount: CGFloat between 0.0 and 1.0. Default value is 0.2.
- returns: A DynamicColor more saturated.
*/
final func saturated(amount: CGFloat = 0.2) -> DynamicColor {
return HSL(color: self).saturated(amount: amount).toDynamicColor()
}
/**
Creates and returns a color object with the saturation decreased by the given amount.
- parameter amount: CGFloat between 0.0 and 1.0. Default value is 0.2.
- returns: A DynamicColor less saturated.
*/
final func desaturated(amount: CGFloat = 0.2) -> DynamicColor {
return HSL(color: self).desaturated(amount: amount).toDynamicColor()
}
/**
Creates and returns a color object converted to grayscale.
- returns: A grayscale DynamicColor.
- seealso: desaturated:
*/
final func grayscaled(mode: GrayscalingMode = .lightness) -> DynamicColor {
let (r, g, b, a) = self.toRGBAComponents()
let l: CGFloat
switch mode {
case .luminance:
l = (0.299 * r) + (0.587 * g) + (0.114 * b)
case .lightness:
l = 0.5 * (max(r, g, b) + min(r, g, b))
case .average:
l = (1.0 / 3.0) * (r + g + b)
case .value:
l = max(r, g, b)
}
return HSL(hue: 0.0, saturation: 0.0, lightness: l, alpha: a).toDynamicColor()
}
/**
Creates and return a color object where the red, green, and blue values are inverted, while the alpha channel is left alone.
- returns: An inverse (negative) of the original color.
*/
final func inverted() -> DynamicColor {
let rgba = toRGBAComponents()
let invertedRed = 1.0 - rgba.r
let invertedGreen = 1.0 - rgba.g
let invertedBlue = 1.0 - rgba.b
return DynamicColor(red: invertedRed, green: invertedGreen, blue: invertedBlue, alpha: rgba.a)
}
}
@@ -0,0 +1,88 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
// MARK: HSB Color Space
extension DynamicColor {
// MARK: - Getting the HSB Components
/**
Returns the HSB (hue, saturation, brightness) components.
- returns: The HSB components as a tuple (h, s, b).
*/
public final func toHSBComponents() -> (h: CGFloat, s: CGFloat, b: CGFloat) {
var h: CGFloat = 0.0
var s: CGFloat = 0.0
var b: CGFloat = 0.0
#if os(iOS) || os(tvOS) || os(watchOS)
getHue(&h, saturation: &s, brightness: &b, alpha: nil)
return (h: h, s: s, b: b)
#elseif os(OSX)
if isEqual(DynamicColor.black) {
return (0.0, 0.0, 0.0)
}
else if isEqual(DynamicColor.white) {
return (0.0, 0.0, 1.0)
}
getHue(&h, saturation: &s, brightness: &b, alpha: nil)
return (h: h, s: s, b: b)
#endif
}
#if os(iOS) || os(tvOS) || os(watchOS)
/**
The hue component as CGFloat between 0.0 to 1.0.
*/
public final var hueComponent: CGFloat {
return toHSBComponents().h
}
/**
The saturation component as CGFloat between 0.0 to 1.0.
*/
public final var saturationComponent: CGFloat {
return toHSBComponents().s
}
/**
The brightness component as CGFloat between 0.0 to 1.0.
*/
public final var brightnessComponent: CGFloat {
return toHSBComponents().b
}
#endif
}
@@ -0,0 +1,65 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
// MARK: HSL Color Space
extension DynamicColor {
/**
Initializes and returns a color object using the specified opacity and HSL component values.
- parameter hue: The hue component of the color object, specified as a value from 0.0 to 360.0 degree.
- parameter saturation: The saturation component of the color object, specified as a value from 0.0 to 1.0.
- parameter lightness: The lightness component of the color object, specified as a value from 0.0 to 1.0.
- parameter alpha: The opacity value of the color object, specified as a value from 0.0 to 1.0. Default to 1.0.
*/
public convenience init(hue: CGFloat, saturation: CGFloat, lightness: CGFloat, alpha: CGFloat = 1) {
let color = HSL(hue: hue, saturation: saturation, lightness: lightness, alpha: alpha).toDynamicColor()
let components = color.toRGBAComponents()
self.init(red: components.r, green: components.g, blue: components.b, alpha: components.a)
}
// MARK: - Getting the HSL Components
/**
Returns the HSL (hue, saturation, lightness) components.
Notes that the hue value is between 0.0 and 360.0 degree.
- returns: The HSL components as a tuple (h, s, l).
*/
public final func toHSLComponents() -> (h: CGFloat, s: CGFloat, l: CGFloat) {
let hsl = HSL(color: self)
return (hsl.h * 360.0, hsl.s, hsl.l)
}
}
@@ -0,0 +1,92 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
// MARK: CIE L*a*b* Color Space
public extension DynamicColor {
/**
Initializes and returns a color object using CIE XYZ color space component values with an observer at 2° and a D65 illuminant.
Notes that values out of range are clipped.
- parameter L: The lightness, specified as a value from 0 to 100.0.
- parameter a: The red-green axis, specified as a value from -128.0 to 127.0.
- parameter b: The yellow-blue axis, specified as a value from -128.0 to 127.0.
- parameter alpha: The opacity value of the color object, specified as a value from 0.0 to 1.0. Default to 1.0.
*/
convenience init(L: CGFloat, a: CGFloat, b: CGFloat, alpha: CGFloat = 1) {
let clippedL = clip(L, 0.0, 100.0)
let clippedA = clip(a, -128.0, 127.0)
let clippedB = clip(b, -128.0, 127.0)
let normalized = { (c: CGFloat) -> CGFloat in
pow(c, 3) > 0.008856 ? pow(c, 3) : (c - (16 / 116)) / 7.787
}
let preY = (clippedL + 16.0) / 116.0
let preX = (clippedA / 500.0) + preY
let preZ = preY - (clippedB / 200.0)
let X = 95.05 * normalized(preX)
let Y = 100.0 * normalized(preY)
let Z = 108.9 * normalized(preZ)
self.init(X: X, Y: Y, Z: Z, alpha: alpha)
}
// MARK: - Getting the L*a*b* Components
/**
Returns the Lab (lightness, red-green axis, yellow-blue axis) components.
It is based on the CIE XYZ color space with an observer at 2° and a D65 illuminant.
Notes that L values are between 0 to 100.0, a values are between -128 to 127.0 and b values are between -128 to 127.0.
- returns: The L*a*b* components as a tuple (L, a, b).
*/
final func toLabComponents() -> (L: CGFloat, a: CGFloat, b: CGFloat) {
let normalized = { (c: CGFloat) -> CGFloat in
c > 0.008856 ? pow(c, 1.0 / 3.0) : (7.787 * c) + (16.0 / 116.0)
}
let xyz = toXYZComponents()
let normalizedX = normalized(xyz.X / 95.05)
let normalizedY = normalized(xyz.Y / 100.0)
let normalizedZ = normalized(xyz.Z / 108.9)
let L = roundDecimal((116.0 * normalizedY) - 16.0, precision: 1000)
let a = roundDecimal(500.0 * (normalizedX - normalizedY), precision: 1000)
let b = roundDecimal(200.0 * (normalizedY - normalizedZ), precision: 1000)
return (L: L, a: a, b: b)
}
}
@@ -0,0 +1,143 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
// MARK: Mixing Colors
public extension DynamicColor {
/**
Mixes the given color object with the receiver.
Specifically, takes the average of each of the RGB components, optionally weighted by the given percentage.
- Parameter color: A color object to mix with the receiver.
- Parameter weight: The weight specifies the amount of the given color object (between 0 and 1).
The default value is 0.5, which means that half the given color and half the receiver color object should be used.
0.25 means that a quarter of the given color object and three quarters of the receiver color object should be used.
- Parameter colorspace: The color space used to mix the colors. By default it uses the RBG color space.
- Returns: A color object corresponding to the two colors object mixed together.
*/
final func mixed(withColor color: DynamicColor, weight: CGFloat = 0.5, inColorSpace colorspace: DynamicColorSpace = .rgb) -> DynamicColor {
let normalizedWeight = clip(weight, 0.0, 1.0)
switch colorspace {
case .lab:
return mixedLab(withColor: color, weight: normalizedWeight)
case .hsl:
return mixedHSL(withColor: color, weight: normalizedWeight)
case .hsb:
return mixedHSB(withColor: color, weight: normalizedWeight)
case .rgb:
return mixedRGB(withColor: color, weight: normalizedWeight)
}
}
/**
Creates and returns a color object corresponding to the mix of the receiver and an amount of white color, which increases lightness.
- Parameter amount: Float between 0.0 and 1.0. The default amount is equal to 0.2.
- Returns: A lighter DynamicColor.
*/
final func tinted(amount: CGFloat = 0.2) -> DynamicColor {
return mixed(withColor: .white, weight: amount)
}
/**
Creates and returns a color object corresponding to the mix of the receiver and an amount of black color, which reduces lightness.
- Parameter amount: Float between 0.0 and 1.0. The default amount is equal to 0.2.
- Returns: A darker DynamicColor.
*/
final func shaded(amount: CGFloat = 0.2) -> DynamicColor {
return mixed(withColor: DynamicColor(red: 0, green: 0, blue: 0, alpha: 1), weight: amount)
}
// MARK: - Convenient Internal Methods
func mixedLab(withColor color: DynamicColor, weight: CGFloat) -> DynamicColor {
let c1 = toLabComponents()
let c2 = color.toLabComponents()
let L = c1.L + (weight * (c2.L - c1.L))
let a = c1.a + (weight * (c2.a - c1.a))
let b = c1.b + (weight * (c2.b - c1.b))
let alpha = alphaComponent + (weight * (color.alphaComponent - alphaComponent))
return DynamicColor(L: L, a: a, b: b, alpha: alpha)
}
func mixedHSL(withColor color: DynamicColor, weight: CGFloat) -> DynamicColor {
let c1 = toHSLComponents()
let c2 = color.toHSLComponents()
let h = c1.h + (weight * mixedHue(source: c1.h, target: c2.h))
let s = c1.s + (weight * (c2.s - c1.s))
let l = c1.l + (weight * (c2.l - c1.l))
let alpha = alphaComponent + (weight * (color.alphaComponent - alphaComponent))
return DynamicColor(hue: h, saturation: s, lightness: l, alpha: alpha)
}
func mixedHSB(withColor color: DynamicColor, weight: CGFloat) -> DynamicColor {
let c1 = toHSBComponents()
let c2 = color.toHSBComponents()
let h = c1.h + (weight * mixedHue(source: c1.h, target: c2.h))
let s = c1.s + (weight * (c2.s - c1.s))
let b = c1.b + (weight * (c2.b - c1.b))
let alpha = alphaComponent + (weight * (color.alphaComponent - alphaComponent))
return DynamicColor(hue: h, saturation: s, brightness: b, alpha: alpha)
}
func mixedRGB(withColor color: DynamicColor, weight: CGFloat) -> DynamicColor {
let c1 = toRGBAComponents()
let c2 = color.toRGBAComponents()
let red = c1.r + (weight * (c2.r - c1.r))
let green = c1.g + (weight * (c2.g - c1.g))
let blue = c1.b + (weight * (c2.b - c1.b))
let alpha = alphaComponent + (weight * (color.alphaComponent - alphaComponent))
return DynamicColor(red: red, green: green, blue: blue, alpha: alpha)
}
func mixedHue(source: CGFloat, target: CGFloat) -> CGFloat {
if target > source && target - source > 180.0 {
return target - source + 360.0
}
else if target < source && source - target > 180.0 {
return target + 360.0 - source
}
return target - source
}
}
@@ -0,0 +1,119 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
// MARK: RGBA Color Space
public extension DynamicColor {
/**
Initializes and returns a color object using the specified opacity and RGB component values.
Notes that values out of range are clipped.
- Parameter r: The red component of the color object, specified as a value from 0.0 to 255.0.
- Parameter g: The green component of the color object, specified as a value from 0.0 to 255.0.
- Parameter b: The blue component of the color object, specified as a value from 0.0 to 255.0.
- Parameter a: The opacity value of the color object, specified as a value from 0.0 to 255.0. The default value is 255.
*/
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 255) {
self.init(red: clip(r, 0, 255) / 255, green: clip(g, 0, 255) / 255, blue: clip(b, 0, 255) / 255, alpha: clip(a, 0, 255) / 255)
}
// MARK: - Getting the RGBA Components
/**
Returns the RGBA (red, green, blue, alpha) components.
- returns: The RGBA components as a tuple (r, g, b, a).
*/
final func toRGBAComponents() -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
#if os(iOS) || os(tvOS) || os(watchOS)
getRed(&r, green: &g, blue: &b, alpha: &a)
return (r, g, b, a)
#elseif os(OSX)
guard let rgbaColor = self.usingColorSpace(.deviceRGB) else {
fatalError("Could not convert color to RGBA.")
}
rgbaColor.getRed(&r, green: &g, blue: &b, alpha: &a)
return (r, g, b, a)
#endif
}
#if os(iOS) || os(tvOS) || os(watchOS)
/**
The red component as CGFloat between 0.0 to 1.0.
*/
final var redComponent: CGFloat {
return toRGBAComponents().r
}
/**
The green component as CGFloat between 0.0 to 1.0.
*/
final var greenComponent: CGFloat {
return toRGBAComponents().g
}
/**
The blue component as CGFloat between 0.0 to 1.0.
*/
final var blueComponent: CGFloat {
return toRGBAComponents().b
}
/**
The alpha component as CGFloat between 0.0 to 1.0.
*/
final var alphaComponent: CGFloat {
return toRGBAComponents().a
}
#endif
// MARK: - Setting the RGBA Components
/**
Creates and returns a color object with the alpha increased by the given amount.
- parameter amount: CGFloat between 0.0 and 1.0.
- returns: A color object with its alpha channel modified.
*/
final func adjustedAlpha(amount: CGFloat) -> DynamicColor {
let components = toRGBAComponents()
let normalizedAlpha = clip(components.a + amount, 0.0, 1.0)
return DynamicColor(red: components.r, green: components.g, blue: components.b, alpha: normalizedAlpha)
}
}
@@ -0,0 +1,89 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
// MARK: CIE XYZ Color Space
public extension DynamicColor {
/**
Initializes and returns a color object using CIE XYZ color space component values with an observer at 2° and a D65 illuminant.
Notes that values out of range are clipped.
- parameter X: The mix of cone response curves, specified as a value from 0 to 95.05.
- parameter Y: The luminance, specified as a value from 0 to 100.0.
- parameter Z: The quasi-equal to blue stimulation, specified as a value from 0 to 108.9.
- parameter alpha: The opacity value of the color object, specified as a value from 0.0 to 1.0. Default to 1.0.
*/
convenience init(X: CGFloat, Y: CGFloat, Z: CGFloat, alpha: CGFloat = 1) {
let clippedX = clip(X, 0.0, 95.05) / 100.0
let clippedY = clip(Y, 0.0, 100) / 100.0
let clippedZ = clip(Z, 0.0, 108.9) / 100.0
let toRGB = { (c: CGFloat) -> CGFloat in
let rgb = c > 0.0031308 ? 1.055 * pow(c, 1.0 / 2.4) - 0.055 : c * 12.92
return abs(roundDecimal(rgb, precision: 1000.0))
}
let red = toRGB((clippedX * 3.2406) + (clippedY * -1.5372) + (clippedZ * -0.4986))
let green = toRGB((clippedX * -0.9689) + (clippedY * 1.8758) + (clippedZ * 0.0415))
let blue = toRGB((clippedX * 0.0557) + (clippedY * -0.2040) + (clippedZ * 1.0570))
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
// MARK: - Getting the XYZ Components
/**
Returns the XYZ (mix of cone response curves, luminance, quasi-equal to blue stimulation) components with an observer at 2° and a D65 illuminant.
Notes that X values are between 0 to 95.05, Y values are between 0 to 100.0 and Z values are between 0 to 108.9.
- returns: The XYZ components as a tuple (X, Y, Z).
*/
final func toXYZComponents() -> (X: CGFloat, Y: CGFloat, Z: CGFloat) {
let toSRGB = { (c: CGFloat) -> CGFloat in
c > 0.04045 ? pow((c + 0.055) / 1.055, 2.4) : c / 12.92
}
let rgba = toRGBAComponents()
let red = toSRGB(rgba.r)
let green = toSRGB(rgba.g)
let blue = toSRGB(rgba.b)
let X = roundDecimal(((red * 0.4124) + (green * 0.3576) + (blue * 0.1805)) * 100.0, precision: 1000.0)
let Y = roundDecimal(((red * 0.2126) + (green * 0.7152) + (blue * 0.0722)) * 100.0, precision: 1000.0)
let Z = roundDecimal(((red * 0.0193) + (green * 0.1192) + (blue * 0.9505)) * 100.0, precision: 1000.0)
return (X: X, Y: Y, Z: Z)
}
}
@@ -0,0 +1,226 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
/**
Extension to manipulate colours easily.
It allows you to work hexadecimal strings and value, HSV and RGB components, derivating colours, and many more...
*/
public typealias DynamicColor = UIColor
#elseif os(OSX)
import AppKit
/**
Extension to manipulate colours easily.
It allows you to work hexadecimal strings and value, HSV and RGB components, derivating colours, and many more...
*/
public typealias DynamicColor = NSColor
#endif
public extension DynamicColor {
// MARK: - Manipulating Hexa-decimal Values and Strings
/**
Creates a color from an hex string (e.g. "#3498db"). The RGBA string are also supported (e.g. "#3498dbff").
If the given hex string is invalid the initialiser will create a black color.
- parameter hexString: A hexa-decimal color string representation.
*/
convenience init(hexString: String) {
let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
var color: UInt64 = 0
if scanner.scanHexInt64(&color) {
self.init(hex: color, useAlpha: hexString.count > 7)
}
else {
self.init(hex: 0x000000)
}
}
/**
Creates a color from an hex integer (e.g. 0x3498db).
- parameter hex: A hexa-decimal UInt64 that represents a color.
- parameter alphaChannel: If true the given hex-decimal UInt64 includes the alpha channel (e.g. 0xFF0000FF).
*/
convenience init(hex: UInt64, useAlpha alphaChannel: Bool = false) {
let mask = UInt64(0xFF)
let cappedHex = !alphaChannel && hex > 0xffffff ? 0xffffff : hex
let r = cappedHex >> (alphaChannel ? 24 : 16) & mask
let g = cappedHex >> (alphaChannel ? 16 : 8) & mask
let b = cappedHex >> (alphaChannel ? 8 : 0) & mask
let a = alphaChannel ? cappedHex & mask : 255
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
let alpha = CGFloat(a) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
/**
Returns the color representation as hexadecimal string.
- returns: A string similar to this pattern "#f4003b".
*/
final func toHexString() -> String {
return String(format: "#%06x", toHex())
}
/**
Returns the color representation as an integer (without the alpha channel).
- returns: A UInt32 that represents the hexa-decimal color.
*/
final func toHex() -> UInt32 {
let rgba = toRGBAComponents()
return roundToHex(rgba.r) << 16 | roundToHex(rgba.g) << 8 | roundToHex(rgba.b)
}
/**
Returns the RGBA color representation.
- returns: A UInt32 that represents the color as an RGBA value.
*/
func toRGBA() -> UInt32 {
let rgba = toRGBAComponents()
return roundToHex(rgba.r) << 24 | roundToHex(rgba.g) << 16 | roundToHex(rgba.b) << 8 | roundToHex(rgba.a)
}
/**
Returns the AGBR color representation.
- returns: A UInt32 that represents the color as an AGBR value.
*/
func toAGBR() -> UInt32 {
let rgba = toRGBAComponents()
return roundToHex(rgba.a) << 24 | roundToHex(rgba.b) << 16 | roundToHex(rgba.g) << 8 | roundToHex(rgba.r)
}
// MARK: - Identifying and Comparing Colors
/**
Returns a boolean value that indicates whether the receiver is equal to the given hexa-decimal string.
- parameter hexString: A hexa-decimal color number representation to be compared to the receiver.
- returns: true if the receiver and the string are equals, otherwise false.
*/
func isEqual(toHexString hexString: String) -> Bool {
return self.toHexString() == hexString
}
/**
Returns a boolean value that indicates whether the receiver is equal to the given hexa-decimal integer.
- parameter hex: A UInt32 that represents the hexa-decimal color.
- returns: true if the receiver and the integer are equals, otherwise false.
*/
func isEqual(toHex hex: UInt32) -> Bool {
return self.toHex() == hex
}
// MARK: - Querying Colors
/**
Determines if the color object is dark or light.
It is useful when you need to know whether you should display the text in black or white.
- returns: A boolean value to know whether the color is light. If true the color is light, dark otherwise.
*/
func isLight() -> Bool {
let components = toRGBAComponents()
let brightness = ((components.r * 299.0) + (components.g * 587.0) + (components.b * 114.0)) / 1000.0
return brightness >= 0.5
}
/**
A float value representing the luminance of the current color. May vary from 0 to 1.0.
We use the formula described by W3C in WCAG 2.0. You can read more here: https://www.w3.org/TR/WCAG20/#relativeluminancedef.
*/
var luminance: CGFloat {
let components = toRGBAComponents()
let componentsArray = [components.r, components.g, components.b].map { (val) -> CGFloat in
guard val <= 0.03928 else { return pow((val + 0.055) / 1.055, 2.4) }
return val / 12.92
}
return (0.2126 * componentsArray[0]) + (0.7152 * componentsArray[1]) + (0.0722 * componentsArray[2])
}
/**
Returns a float value representing the contrast ratio between 2 colors.
We use the formula described by W3C in WCAG 2.0. You can read more here: https://www.w3.org/TR/WCAG20-TECHS/G18.html
NB: the contrast ratio is a relative value. So the contrast between Color1 and Color2 is exactly the same between Color2 and Color1.
- returns: A CGFloat representing contrast value.
*/
func contrastRatio(with otherColor: DynamicColor) -> CGFloat {
let otherLuminance = otherColor.luminance
let l1 = max(luminance, otherLuminance)
let l2 = min(luminance, otherLuminance)
return (l1 + 0.05) / (l2 + 0.05)
}
/**
Indicates if two colors are contrasting, regarding W3C's WCAG 2.0 recommendations.
You can read it here: https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast
The acceptable contrast ratio depends on the context of display. Most of the time, the default context (.Standard) is enough.
You can look at ContrastDisplayContext for more options.
- parameter otherColor: The other color to compare with.
- parameter context: An optional context to determine the minimum acceptable contrast ratio. Default value is .Standard.
- returns: true is the contrast ratio between 2 colors exceed the minimum acceptable ratio.
*/
func isContrasting(with otherColor: DynamicColor, inContext context: ContrastDisplayContext = .standard) -> Bool {
return self.contrastRatio(with: otherColor) > context.minimumContrastRatio
}
}
@@ -0,0 +1,105 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
/**
Object representing a gradient object. It allows you to manipulate colors inside different gradients and color spaces.
*/
final public class DynamicGradient {
let colors: [DynamicColor]
/**
Initializes and creates a gradient from a color array.
- Parameter colors: An array of colors.
*/
public init(colors: [DynamicColor]) {
self.colors = colors
}
/**
Returns the color palette of `amount` elements by grabbing equidistant colors.
- Parameter amount: An amount of colors to return. 2 by default.
- Parameter colorspace: The color space used to mix the colors. By default it uses the RBG color space.
- Returns: An array of DynamicColor objects with equi-distant space in the gradient.
*/
public func colorPalette(amount: UInt = 2, inColorSpace colorspace: DynamicColorSpace = .rgb) -> [DynamicColor] {
guard amount > 0 && colors.count > 0 else {
return []
}
guard colors.count > 1 else {
return (0 ..< amount).map { _ in colors[0] }
}
let increment = 1.0 / CGFloat(amount - 1)
return (0 ..< amount).map { pickColorAt(scale: CGFloat($0) * increment, inColorSpace: colorspace) }
}
/**
Picks up and returns the color at the given scale by interpolating the colors.
For example, given this color array `[red, green, blue]` and a scale of `0.25` you will get a kaki color.
- Parameter scale: A float value between 0.0 and 1.0.
- Parameter colorspace: The color space used to mix the colors. By default it uses the RBG color space.
- Returns: A DynamicColor object corresponding to the color at the given scale.
*/
public func pickColorAt(scale: CGFloat, inColorSpace colorspace: DynamicColorSpace = .rgb) -> DynamicColor {
guard colors.count > 1 else {
return colors.first ?? .black
}
let clippedScale = clip(scale, 0.0, 1.0)
let positions = (0 ..< colors.count).map { CGFloat($0) / CGFloat(colors.count - 1) }
var color: DynamicColor = .black
for (index, position) in positions.enumerated() {
guard clippedScale <= position else { continue }
guard clippedScale != 0.0 && clippedScale != 1.0 else {
return colors[index]
}
let previousPosition = positions[index - 1]
let weight = (clippedScale - previousPosition) / (position - previousPosition)
color = colors[index - 1].mixed(withColor: colors[index], weight: weight, inColorSpace: colorspace)
break
}
return color
}
}
@@ -0,0 +1,39 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/**
Defines the supported color spaces.
*/
public enum DynamicColorSpace {
/// The RGB color space
case rgb
/// The HSL color space
case hsl
/// The HSB color space
case hsb
/// The Cie L*a*b* color space
case lab
}
@@ -0,0 +1,41 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/**
Defines the mode (i.e color space) used for grayscaling.
[More info](https://en.wikipedia.org/wiki/Lightness#Lightness_and_human_perception)
*/
public enum GrayscalingMode {
/// XYZ luminance
case luminance
/// HSL lightness
case lightness
/// RGB average
case average
/// HSV value
case value
}
@@ -0,0 +1,196 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import SwiftUI
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
/// Hue-saturation-lightness structure to make the color manipulation easier.
internal struct HSL {
/// Hue value between 0.0 and 1.0 (0.0 = 0 degree, 1.0 = 360 degree).
var h: CGFloat = 0.0
/// Saturation value between 0.0 and 1.0.
var s: CGFloat = 0.0
/// Lightness value between 0.0 and 1.0.
var l: CGFloat = 0.0
/// Alpha value between 0.0 and 1.0.
var a: CGFloat = 1.0
// MARK: - Initializing HSL Colors
/**
Initializes and creates a HSL color from the hue, saturation, lightness and alpha components.
- parameter h: The hue component of the color object, specified as a value between 0.0 and 360.0 degree.
- parameter s: The saturation component of the color object, specified as a value between 0.0 and 1.0.
- parameter l: The lightness component of the color object, specified as a value between 0.0 and 1.0.
- parameter a: The opacity component of the color object, specified as a value between 0.0 and 1.0.
*/
init(hue: CGFloat, saturation: CGFloat, lightness: CGFloat, alpha: CGFloat = 1.0) {
h = hue.truncatingRemainder(dividingBy: 360.0) / 360.0
s = clip(saturation, 0.0, 1.0)
l = clip(lightness, 0.0, 1.0)
a = clip(alpha, 0.0, 1.0)
}
/**
Initializes and creates a HSL (hue, saturation, lightness) color from a DynamicColor object.
- parameter color: A DynamicColor object.
*/
init(color: DynamicColor) {
let rgba = color.toRGBAComponents()
let maximum = max(rgba.r, max(rgba.g, rgba.b))
let minimum = min(rgba.r, min(rgba.g, rgba.b))
let delta = maximum - minimum
h = 0.0
s = 0.0
l = (maximum + minimum) / 2.0
if delta != 0.0 {
if l < 0.5 {
s = delta / (maximum + minimum)
}
else {
s = delta / (2.0 - maximum - minimum)
}
if rgba.r == maximum {
h = ((rgba.g - rgba.b) / delta) + (rgba.g < rgba.b ? 6.0 : 0.0)
}
else if rgba.g == maximum {
h = ((rgba.b - rgba.r) / delta) + 2.0
}
else if rgba.b == maximum {
h = ((rgba.r - rgba.g) / delta) + 4.0
}
}
h /= 6.0
a = rgba.a
}
// MARK: - Transforming HSL Color
/**
Returns the DynamicColor representation from the current HSV color.
- returns: A DynamicColor object corresponding to the current HSV color.
*/
func toDynamicColor() -> DynamicColor {
let (r, g, b, a) = rgbaComponents()
return DynamicColor(red: r, green: g, blue: b, alpha: a)
}
/// Returns the RGBA components from the current HSV color.
func rgbaComponents() -> (CGFloat, CGFloat, CGFloat, CGFloat) {
let m2 = l <= 0.5 ? l * (s + 1.0) : (l + s) - (l * s)
let m1 = (l * 2.0) - m2
let r = hueToRGB(m1: m1, m2: m2, h: h + (1.0 / 3.0))
let g = hueToRGB(m1: m1, m2: m2, h: h)
let b = hueToRGB(m1: m1, m2: m2, h: h - (1.0 / 3.0))
return (r, g, b, CGFloat(a))
}
/// Hue to RGB helper function
private func hueToRGB(m1: CGFloat, m2: CGFloat, h: CGFloat) -> CGFloat {
let hue = moda(h, m: 1)
if hue * 6 < 1.0 {
return m1 + ((m2 - m1) * hue * 6.0)
}
else if hue * 2.0 < 1.0 {
return m2
}
else if hue * 3.0 < 1.9999 {
return m1 + ((m2 - m1) * ((2.0 / 3.0) - hue) * 6.0)
}
return m1
}
// MARK: - Deriving the Color
/**
Returns a color with the hue rotated along the color wheel by the given amount.
- parameter amount: A float representing the number of degrees as ratio (usually between -360.0 degree and 360.0 degree).
- returns: A HSL color with the hue changed.
*/
func adjustedHue(amount: CGFloat) -> HSL {
return HSL(hue: (h * 360.0) + amount, saturation: s, lightness: l, alpha: a)
}
/**
Returns a color with the lightness increased by the given amount.
- parameter amount: CGFloat between 0.0 and 1.0.
- returns: A lighter HSL color.
*/
func lighter(amount: CGFloat) -> HSL {
return HSL(hue: h * 360.0, saturation: s, lightness: l + amount, alpha: a)
}
/**
Returns a color with the lightness decreased by the given amount.
- parameter amount: CGFloat between 0.0 and 1.0.
- returns: A darker HSL color.
*/
func darkened(amount: CGFloat) -> HSL {
return lighter(amount: amount * -1.0)
}
/**
Returns a color with the saturation increased by the given amount.
- parameter amount: CGFloat between 0.0 and 1.0.
- returns: A HSL color more saturated.
*/
func saturated(amount: CGFloat) -> HSL {
return HSL(hue: h * 360.0, saturation: s + amount, lightness: l, alpha: a)
}
/**
Returns a color with the saturation decreased by the given amount.
- parameter amount: CGFloat between 0.0 and 1.0.
- returns: A HSL color less saturated.
*/
func desaturated(amount: CGFloat) -> HSL {
return saturated(amount: amount * -1.0)
}
}
@@ -0,0 +1,73 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
/**
Clips the values in an interval.
Given an interval, values outside the interval are clipped to the interval
edges. For example, if an interval of [0, 1] is specified, values smaller than
0 become 0, and values larger than 1 become 1.
- Parameter v: The value to clipped.
- Parameter minimum: The minimum edge value.
- Parameter maximum: The maximum edgevalue.
*/
internal func clip<T: Comparable>(_ v: T, _ minimum: T, _ maximum: T) -> T {
return max(min(v, maximum), minimum)
}
/**
Returns the absolute value of the modulo operation.
- Parameter x: The value to compute.
- Parameter m: The modulo.
*/
internal func moda(_ x: CGFloat, m: CGFloat) -> CGFloat {
return (x.truncatingRemainder(dividingBy: m) + m).truncatingRemainder(dividingBy: m)
}
/**
Rounds the given float to a given decimal precision.
- Parameter x: The value to round.
- Parameter m: The precision. Default to 10000.
*/
internal func roundDecimal(_ x: CGFloat, precision: CGFloat = 10000.0) -> CGFloat {
return CGFloat(Int(round(x * precision))) / precision
}
internal func roundToHex(_ x: CGFloat) -> UInt32 {
guard x > 0 else { return 0 }
let rounded: CGFloat = round(x * 255.0)
return UInt32(rounded)
}
@@ -0,0 +1,77 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import SwiftUI
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
public extension Color {
// MARK: - Manipulating Hexa-decimal Values and Strings
/**
Creates a color from an hex string (e.g. "#3498db"). The RGBA string are also supported (e.g. "#3498dbff").
If the given hex string is invalid the initialiser will create a black color.
- parameter hexString: A hexa-decimal color string representation.
*/
init(hexString: String) {
let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
var color: UInt64 = 0
if scanner.scanHexInt64(&color) {
self.init(hex: color, useOpacity: hexString.count > 7)
}
else {
self.init(hex: 0x000000)
}
}
/**
Creates a color from an hex integer (e.g. 0x3498db).
- parameter hex: A hexa-decimal UInt64 that represents a color.
- parameter opacityChannel: If true the given hex-decimal UInt64 includes the opacity channel (e.g. 0xFF0000FF).
*/
init(hex: UInt64, useOpacity opacityChannel: Bool = false) {
let mask = UInt64(0xFF)
let cappedHex = !opacityChannel && hex > 0xffffff ? 0xffffff : hex
let r = cappedHex >> (opacityChannel ? 24 : 16) & mask
let g = cappedHex >> (opacityChannel ? 16 : 8) & mask
let b = cappedHex >> (opacityChannel ? 8 : 0) & mask
let o = opacityChannel ? cappedHex & mask : 255
let red = Double(r) / 255.0
let green = Double(g) / 255.0
let blue = Double(b) / 255.0
let opacity = Double(o) / 255.0
self.init(red: red, green: green, blue: blue, opacity: opacity)
}
}
@@ -0,0 +1,46 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import SwiftUI
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
/// Convert a DynamicColor to a SwiftUI color
extension DynamicColor {
/**
Returns the Color from an Dynamic Color.
- returns: A Color (SwiftUI).
*/
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
func toColor() -> Color {
return Color(self)
}
}
@@ -0,0 +1,37 @@
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import SwiftUI
extension HSL {
@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
func toColor() -> Color {
let (r, g, b, a) = rgbaComponents()
return SwiftUI.Color(red: Double(r), green: Double(g), blue: Double(b), opacity: Double(a))
}
}
@@ -0,0 +1,257 @@
//
// HomeView.swift
// XuXuCheck
//
// Created by henseycai on 2025/6/11.
//
import SwiftUI
struct HomeView: View {
@State var hasScroll = false
@Namespace var namespace
@State var showMods: Bool = false
@State var showStatusBar = true
@State var selectedID = UUID()
@Environment(Status.self) var status
@Environment(LoginStatus.self) var loginStatus
var body: some View {
ZStack {
Color("background").ignoresSafeArea()
ScrollView {
scrollDetection
//featured
HomeScanView().padding(20)
LazyVGrid(columns: [GridItem(.adaptive(minimum: 140), spacing: 20)]) {
homeModCards
}
.padding(.horizontal, 20)
}
.coordinateSpace(name: "scroll")
.safeAreaInset(edge: .top, content: {
Color.clear.frame(height: 70)
})
.overlay(
NavigationBar(title: Storage.shared.member_name, hasScrolled: $hasScroll)
)
}
.statusBar(hidden: !showStatusBar)
.fullScreenCover(isPresented: $showMods) {
if let idx = homeFuncblocks.firstIndex(where: {$0.id == selectedID}){
if let url = homeFuncblocks[idx].link {
if(url.contains(API.webrecordUrl) && loginStatus.isLogin == false){
LoginView()
}else{
XuXuWebView(currentUrl: url)
}
}
}
}
}
var scrollDetection: some View {
GeometryReader { proxy in
Color.clear
.preference(key: ScrollPreferenceKey.self, value: proxy.frame(in: .named("scroll")).minY)
}
.frame(height: 0)
.onPreferenceChange(ScrollPreferenceKey.self, perform: { value in
withAnimation(.easeInOut) {
if value < 0 {
hasScroll = true
} else {
hasScroll = false
}
}
})
}
struct HomeScanView: View {
let bgcolor = Color(hex: 0x2449f1)
let bgcolor2 = Color(hex: 0x1638d9)
let scale = 9.0
@State private var moveOnCircularPath: Bool = false
@State var showModal = false
@Environment(LoginStatus.self) var loginStatus
var body: some View {
VStack {
ZStack {
Circle()
.stroke(bgcolor,lineWidth: scale * 2)
.frame(width: 26*scale, height: 26*scale)
Circle()
.stroke(bgcolor2,lineWidth: scale)
.frame(width: 23.5*scale, height: 23.5*scale)
Image("lay_cycle1")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 22.5*scale,height: 22.5*scale)
Image("ball2")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 18*scale,height: 18*scale)
Image("lay3")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 18*scale,height: 18*scale)
Image("lay5")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 18*scale,height: 18*scale)
Image("lay4")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 18*scale,height: 18*scale)
Image("lay6")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 4*scale,height: 4*scale)
Image("ball")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 2.2*scale,height: 2.2*scale).offset(x:0,y:10*scale)
.rotationEffect(.degrees(moveOnCircularPath ? 0 : -360))
.task {
withAnimation(.myLinear.delay(0).repeatForever(autoreverses: false)) {
moveOnCircularPath.toggle()
}
}
}.overlay(txtOverlay.offset(x:0,y: -(6*scale)),alignment: .bottom)
}
.onTapGesture {
showModal.toggle()
}
.fullScreenCover(isPresented: $showModal) {
if(loginStatus.isLogin){
ScanView()
}else{
LoginView()
}
}
}
private var txtOverlay: some View {
ZStack{
// Capsule()
// .fill(Color.white.opacity(0.5))
// .frame(width: 120, height: 50)
Text("SCAN").font(.title)
.foregroundColor(.yellow)
}
}
}
var homeModCards : some View {
ForEach(homeFuncblocks ) { block in
Button(action: {
showMods.toggle()
//status.showNavDetail.toggle()
//status.showNavDetail = true
showStatusBar = false
selectedID = block.id
}, label: {
HomeCardItem(namespace: namespace,
block: block,
showMods: $showMods)
})
}
}
struct HomeCardItem: View {
var namespace: Namespace.ID
var block: BlockItem = homeFuncblocks[0]
@Binding var showMods: Bool
var body: some View {
VStack {
Spacer()
VStack(alignment: .center) {
Image(block.image)
.resizable().frame(width: 56,height: 56)
.aspectRatio(contentMode: .fit)
.matchedGeometryEffect(id: "image\(block.id)", in: namespace)
Text(block.title)
.font(.headline.weight(.bold))
.matchedGeometryEffect(id: "title\(block.id)", in: namespace)
.frame(maxWidth: .infinity, alignment: .center)
}
.padding(16)
.background(
Rectangle()
.fill(.ultraThinMaterial)
.mask(RoundedRectangle(cornerRadius: 30, style: .continuous))
.blur(radius: 30)
.matchedGeometryEffect(id: "blur\(block.id)", in: namespace)
)
}
.foregroundStyle(.white)
.background(
Image(block.background)
.resizable()
.aspectRatio(contentMode: .fill)
.matchedGeometryEffect(id: "background\(block.id)", in: namespace)
)
.mask(RoundedRectangle(cornerRadius: 30, style: .continuous)
.matchedGeometryEffect(id: "mask\(block.id)", in: namespace))
.frame(height: 132)
}
}
struct HomeCardItem_Previews: PreviewProvider {
@Namespace static var namespace
static var previews: some View {
HomeCardItem(namespace: namespace, showMods: .constant(true))
}
}
}
#Preview {
HomeView()
}
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="22113.3" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina6_12" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="22089.1"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="393" height="852"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="obG-Y5-kRd">
<rect key="frame" x="0.0" y="832" width="393" height="0.0"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="XuXuCheck" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="GJd-Yh-RWb">
<rect key="frame" x="0.0" y="263.66666666666669" width="393" height="43"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Copyright © 2025 Niaodaifu. All rights reserved" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="QPA-bD-3gk">
<rect key="frame" x="0.0" y="797" width="393" height="21"/>
<constraints>
<constraint firstAttribute="height" constant="21" id="qUJ-kC-I5x"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="12"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<viewLayoutGuide key="safeArea" id="Bcu-3y-fUS"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="Bcu-3y-fUS" firstAttribute="trailing" secondItem="QPA-bD-3gk" secondAttribute="trailing" id="025-Zb-SLS"/>
<constraint firstItem="Bcu-3y-fUS" firstAttribute="centerX" secondItem="obG-Y5-kRd" secondAttribute="centerX" id="5cz-MP-9tL"/>
<constraint firstItem="QPA-bD-3gk" firstAttribute="bottom" secondItem="Bcu-3y-fUS" secondAttribute="bottom" id="8wn-Uh-Nmb"/>
<constraint firstItem="Bcu-3y-fUS" firstAttribute="centerX" secondItem="GJd-Yh-RWb" secondAttribute="centerX" id="Q3B-4B-g5h"/>
<constraint firstItem="obG-Y5-kRd" firstAttribute="leading" secondItem="Bcu-3y-fUS" secondAttribute="leading" constant="20" symbolic="YES" id="SfN-ll-jLj"/>
<constraint firstAttribute="bottom" secondItem="obG-Y5-kRd" secondAttribute="bottom" constant="20" id="Y44-ml-fuU"/>
<constraint firstItem="GJd-Yh-RWb" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="bottom" multiplier="1/3" constant="1" id="moa-c2-u7t"/>
<constraint firstItem="GJd-Yh-RWb" firstAttribute="leading" secondItem="Bcu-3y-fUS" secondAttribute="leading" constant="20" symbolic="YES" id="x7j-FC-K8j"/>
<constraint firstItem="QPA-bD-3gk" firstAttribute="leading" secondItem="Bcu-3y-fUS" secondAttribute="leading" id="zfx-wW-kLB"/>
</constraints>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-375" y="379"/>
</scene>
</scenes>
</document>

Some files were not shown because too many files have changed in this diff Show More