我正在学习迅速,我正在上课。我们被告知要编写一个代码,将滤镜应用于样本图片,以更改其参数中图像上给定的颜色强度,然后返回修改后的图像。
在我编写的代码中,在最后几行中,它表示错误说
在预期返回'UIImage'的函数中缺少返回
我的班级代码:
import UIKit
let image = UIImage(named: "sample")!
class brightnessFilter {
func increaseContrast(image: UIImage) -> UIImage{
var rgbaImage = RGBAImage(image: image)!
let avgRed = 118
let avgGreen = 98
let avgBlue = 83
for y in 0..<rgbaImage.height {
for x in 0..<rgbaImage.width {
let index = y * rgbaImage.width + x
var pixel = rgbaImage.pixels[index]
let redLum = Int(pixel.red) - avgRed
let greenLum = Int(pixel.green) - avgGreen
let blueLum = Int(pixel.blue) - avgBlue
pixel.red = UInt8(max(min(255, avgRed + 2 * redLum), 0))
pixel.blue = UInt8(max(min(255, avgBlue + 2 * blueLum), 0))
pixel.green = UInt8(max(min(255, avgGreen + 2 * greenLum), 0))
rgbaImage.pixels[index] = pixel
}
}
let newImage1 = rgbaImage.toUIImage()!
return (newImage1)
}
}
let test = brightnessFilter()
let processedImg = test.increaseContrast(image)
class redFilter {
func increaseContrast(image: UIImage) -> UIImage{
var rgbaImage = RGBAImage(image: image)!
let avgRed = 118
for y in 0..<rgbaImage.height {
for x in 0..<rgbaImage.width {
let index = y * rgbaImage.width + x
var pixel = rgbaImage.pixels[index]
let redDiff = Int(pixel.red) - avgRed
if (redDiff > 0) {
pixel.red = UInt8( max(0, min(255, avgRed + redDiff * 5)))
rgbaImage.pixels[index] = pixel
}
}
let newImage2 = rgbaImage.toUIImage()!
return (newImage2)
}
}
}
let test2 = redFilter()
RGBA课程:
import UIKit
public struct Pixel {
public var value: UInt32
public var red: UInt8 {
get {
return UInt8(value & 0xFF)
}
set {
value = UInt32(newValue) | (value & 0xFFFFFF00)
}
}
public var green: UInt8 {
get {
return UInt8((value >> 8) & 0xFF)
}
set {
value = (UInt32(newValue) << 8) | (value & 0xFFFF00FF)
}
}
public var blue: UInt8 {
get {
return UInt8((value >> 16) & 0xFF)
}
set {
value = (UInt32(newValue) << 16) | (value & 0xFF00FFFF)
}
}
public var alpha: UInt8 {
get {
return UInt8((value >> 24) & 0xFF)
}
set {
value = (UInt32(newValue) << 24) | (value & 0x00FFFFFF)
}
}
}
答案 0 :(得分:0)
当使用返回值写入方法声明时,必须确保它始终返回一个值。
我相信您的错误在以下方法中:
func increaseContrast(image: UIImage) -> UIImage {
var rgbaImage = RGBAImage(image: image)!
let avgRed = 118
let newImage2 = UIImage() //<-- Added
for y in 0..<rgbaImage.height {
for x in 0..<rgbaImage.width {
let index = y * rgbaImage.width + x
var pixel = rgbaImage.pixels[index]
let redDiff = Int(pixel.red) - avgRed
if (redDiff > 0) {
pixel.red = UInt8( max(0, min(255, avgRed + redDiff * 5)))
rgbaImage.pixels[index] = pixel
}
}
let newImage2 = rgbaImage.toUIImage()!
return (newImage2) //<---NOTICE
}// <---FIX
}
注意:return
语句位于for
循环中,这意味着该方法可能并不总是返回值。
修复:将return语句放在代码中标记的花括号下。
已添加:您必须返回一个值,因此,您必须创建一个
附注:确保处理nil