【swiftUI】图片直方图信息提取示例代码
效果展示:

代码示例:
//
// ContentView.swift
// AestheticDiary
//
// Created by liulin on 2025/10/19.
//
import SwiftUI
import CoreImage
import CoreImage.CIFilterBuiltins
// MARK: - 直方图数据结构
struct HistogramData {
let red: [Int]
let green: [Int]
let blue: [Int]
init(red: [Int] = Array(repeating: 0, count: 256),
green: [Int] = Array(repeating: 0, count: 256),
blue: [Int] = Array(repeating: 0, count: 256)) {
self.red = red
self.green = green
self.blue = blue
}
}
// MARK: - 直方图视图 (Photoshop 风格)
struct HistogramView: View {
let histogramData: HistogramData
let maxValue: Int
init(histogramData: HistogramData) {
self.histogramData = histogramData
self.maxValue = max(
histogramData.red.max() ?? 0,
histogramData.green.max() ?? 0,
histogramData.blue.max() ?? 0
)
}
var body: some View {
VStack(spacing: 12) {
Text("RGB 直方图")
.font(.headline)
.padding(.bottom, 4)
// Photoshop 风格的叠加直方图
ZStack {
// 背景网格
// HistogramGrid()
// 叠加的 RGB 通道
HistogramOverlay(histogramData: histogramData, maxValue: maxValue)
}
.frame(height: 150)
.background(Color.black.opacity(0.05))
.overlay(
RoundedRectangle(cornerRadius: 0)
.stroke(Color.gray.opacity(0.05), lineWidth: 1)
)
// 图例
HStack(spacing: 20) {
HStack(spacing: 4) {
Rectangle()
.fill(Color.red)
.frame(width: 12, height: 8)
Text("红色")
.font(.caption)
.foregroundColor(.red)
}
HStack(spacing: 4) {
Rectangle()
.fill(Color.green)
.frame(width: 12, height: 8)
Text("绿色")
.font(.caption)
.foregroundColor(.green)
}
HStack(spacing: 4) {
Rectangle()
.fill(Color.blue)
.frame(width: 12, height: 8)
Text("蓝色")
.font(.caption)
.foregroundColor(.blue)
}
}
}
.padding()
.background(Color.gray.opacity(0.1))
}
}
// MARK: - 直方图网格背景
struct HistogramGrid: View {
var body: some View {
GeometryReader { geometry in
VStack(spacing: 0) {
ForEach(0..<5, id: \.self) { _ in
Rectangle()
.fill(Color.gray.opacity(0.2))
.frame(height: 1)
Spacer()
}
}
.frame(height: geometry.size.height)
HStack(spacing: 0) {
ForEach(0..<5, id: \.self) { _ in
Rectangle()
.fill(Color.gray.opacity(0.2))
.frame(width: 1)
Spacer()
}
}
.frame(width: geometry.size.width)
}
}
}
// MARK: - 叠加直方图 (Photoshop 风格)
struct HistogramOverlay: View {
let histogramData: HistogramData
let maxValue: Int
var body: some View {
GeometryReader { geometry in
ZStack {
// 红色通道
HistogramChannel(
data: histogramData.red,
color: .red,
maxValue: maxValue,
geometry: geometry
)
// 绿色通道
HistogramChannel(
data: histogramData.green,
color: .green,
maxValue: maxValue,
geometry: geometry
)
// 蓝色通道
HistogramChannel(
data: histogramData.blue,
color: .blue,
maxValue: maxValue,
geometry: geometry
)
}
}
}
}
// MARK: - 单个通道直方图
struct HistogramChannel: View {
let data: [Int]
let color: Color
let maxValue: Int
let geometry: GeometryProxy
var body: some View {
Path { path in
let width = geometry.size.width
let height = geometry.size.height
let stepX = width / CGFloat(data.count)
var points: [CGPoint] = []
for (index, value) in data.enumerated() {
let x = CGFloat(index) * stepX
let normalizedValue = maxValue > 0 ? CGFloat(value) / CGFloat(maxValue) : 0
let y = height - (normalizedValue * height)
points.append(CGPoint(x: x, y: y))
}
if !points.isEmpty {
path.move(to: points[0])
for point in points.dropFirst() {
path.addLine(to: point)
}
}
}
.stroke(color, lineWidth: 1.5)
.opacity(0.8)
}
}
// MARK: - 主页面
struct ContentView: View {
@State private var histogramData: HistogramData = HistogramData()
@State private var isAnalyzed = false
@State private var isAnalyzing = false
var body: some View {
ScrollView {
VStack(spacing: 20) {
// 标题
Text("图片直方图分析 Demo")
.font(.largeTitle)
.fontWeight(.bold)
.padding(.top)
// 默认图片展示
Image("person")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxHeight: 300)
.cornerRadius(12)
.shadow(radius: 4)
// 分析按钮
Button(action: analyzeImage) {
HStack {
if isAnalyzing {
ProgressView()
.scaleEffect(0.8)
.progressViewStyle(CircularProgressViewStyle(tint: .white))
}
Text(isAnalyzing ? "分析中..." : "重新分析图片直方图")
}
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(8)
}
.disabled(isAnalyzing)
// 直方图展示
if isAnalyzed {
HistogramView(histogramData: histogramData)
.transition(.opacity.combined(with: .scale))
}
// 分析结果统计
if isAnalyzed {
VStack(alignment: .leading, spacing: 8) {
Text("分析结果")
.font(.headline)
HStack {
VStack(alignment: .leading) {
Text("红色通道:")
.foregroundColor(.red)
Text("最大值: \(histogramData.red.max() ?? 0)")
Text("平均值: \(Int(histogramData.red.reduce(0, +) / histogramData.red.count))")
}
Spacer()
VStack(alignment: .leading) {
Text("绿色通道:")
.foregroundColor(.green)
Text("最大值: \(histogramData.green.max() ?? 0)")
Text("平均值: \(Int(histogramData.green.reduce(0, +) / histogramData.green.count))")
}
Spacer()
VStack(alignment: .leading) {
Text("蓝色通道:")
.foregroundColor(.blue)
Text("最大值: \(histogramData.blue.max() ?? 0)")
Text("平均值: \(Int(histogramData.blue.reduce(0, +) / histogramData.blue.count))")
}
}
.font(.caption)
}
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(8)
}
}
.padding()
.onAppear {
print("答应")
analyzeImage()
}
}
}
// MARK: - 图片分析方法
private func analyzeImage() {
isAnalyzing = true
isAnalyzed = false
DispatchQueue.global(qos: .userInitiated).async {
guard let image = UIImage(named: "person"),
let cgImage = image.cgImage else {
DispatchQueue.main.async { self.isAnalyzing = false }
return
}
let width = cgImage.width
let height = cgImage.height
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let totalBytes = height * bytesPerRow
var pixelData = [UInt8](repeating: 0, count: totalBytes)
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let context = CGContext(data: &pixelData,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
DispatchQueue.main.async { self.isAnalyzing = false }
return
}
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
// 初始化直方图
var redHistogram = Array(repeating: 0, count: 256)
var greenHistogram = Array(repeating: 0, count: 256)
var blueHistogram = Array(repeating: 0, count: 256)
// 遍历每个像素
for i in stride(from: 0, to: totalBytes, by: bytesPerPixel) {
let r = Int(pixelData[i])
let g = Int(pixelData[i + 1])
let b = Int(pixelData[i + 2])
redHistogram[r] += 1
greenHistogram[g] += 1
blueHistogram[b] += 1
}
DispatchQueue.main.async {
self.histogramData = HistogramData(red: redHistogram, green: greenHistogram, blue: blueHistogram)
self.isAnalyzed = true
self.isAnalyzing = false
}
}
}
}
// SwiftUI预览:用于Xcode中的实时预览功能
#Preview {
ContentView() // 预览ContentView
}
许可协议:
CC BY 4.0