Metal每日分享,调整图片角度滤镜效果

2022-11-27  本文已影响0人  弹吉他的少年

本案例的目的是理解如何用Metal实现调节图片角度滤镜,通过修改画布大小,取出旋转之后的坐标点像素来达到旋转效果;


效果图

WX20221125-112918.png

Demo

实操代码

// 旋转滤镜
let filter = C7Rotate.init(angle: 180)

// 方案1:
let dest = BoxxIO.init(element: originImage, filter: filter)
ImageView.image = try? dest.output()

dest.filters.forEach {
    NSLog("%@", "\($0.parameterDescription)")
}

// 方案2:
ImageView.image = try? originImage.make(filter: filter)

// 方案3:
ImageView.image = originImage ->> filter

实现原理

这款滤镜采用并行计算编码器设计.compute(kernel: "C7Rotate"),参数因子[Degree(value: angle).radians]

对外开放参数

/// 旋转
public struct C7Rotate: C7FilterProtocol {
    
    /// Angle to rotate, unit is degree
    @DegreeRange public var angle: Float
    
    public var modifier: Modifier {
        return .compute(kernel: "C7Rotate")
    }
    
    public var factors: [Float] {
        return [Degree(value: angle).radians]
    }
    
    public func outputSize(input size: C7Size) -> C7Size {
        return mode.rotate(angle: Degree(value: angle).radians, size: size)
    }
    
    private var mode: ShapeMode = .fitSize
    
    public init(mode: ShapeMode = .fitSize, angle: Float = 0) {
        self.angle = angle
        self.mode = mode
    }
}

将角度控制在0 ~ 360范围之间,

/// `0.0 ..< 360.0` 范围角度区间属性包装器
@propertyWrapper public struct DegreeRange {
    
    public var wrappedValue: Float {
        didSet {
            let value = wrappedValue.truncatingRemainder(dividingBy: 360.0)
            wrappedValue = value >= 0 ? value : 360 + value
        }
    }
    
    public init(wrappedValue: Float) {
        let value = wrappedValue.truncatingRemainder(dividingBy: 360.0)
        self.wrappedValue = value >= 0 ? value : 360 + value
    }
}

将角度转换成弧度供着色器使用,

public struct Degree {
    
    public let value: Float
    
    public var radians: Float {
        return Float(value * Float.pi / 180.0)
    }
}

// MARK - Negative Degrees
public prefix func -(degree: Degree) -> Degree {
    return Degree(value: -1 * degree.value)
}

计算旋转之后的尺寸

public func rotate(angle: Float, size: C7Size) -> C7Size {
    switch self {
    case .none:
        return size
    case .fitSize:
        let w = Int(abs(sin(angle) * Float(size.height)) + abs(cos(angle) * Float(size.width)))
        let h = Int(abs(sin(angle) * Float(size.width)) + abs(cos(angle) * Float(size.height)))
        return C7Size(width: w, height: h)
    }
}

获取新画布尺寸然后再对坐标点归一化处理,计算超出部分角度,然后算出点坐标(inX, inY)取出对应点的像素,超出部分则用空像素填充;

kernel void C7Rotate(texture2d<half, access::write> outputTexture [[texture(0)]],
                     texture2d<half, access::sample> inputTexture [[texture(1)]],
                     constant float *angle [[buffer(0)]],
                     uint2 grid [[thread_position_in_grid]]) {
    const float outX = float(grid.x) - outputTexture.get_width() / 2.0f;
    const float outY = float(grid.y) - outputTexture.get_height() / 2.0f;
    const float dd = distance(float2(outX, outY), float2(0, 0));
    const float pi = 3.14159265358979323846264338327950288;
    const float w = inputTexture.get_width();
    const float h = inputTexture.get_height();
    float outAngle = atan(outY / outX);
    if (outX < 0) { outAngle += pi; };
    const float inAngle = outAngle - float(*angle);
    const float inX = (cos(inAngle) * dd + w / 2.0f) / w;
    const float inY = (sin(inAngle) * dd + h / 2.0f) / h;
    
    // Set empty pixel when out of range
    if (inX * w < -1 || inX * w > w + 1 || inY * h < -1 || inY * h > h + 1) {
        outputTexture.write(half4(0), grid);
        return;
    }
    
    constexpr sampler quadSampler(mag_filter::linear, min_filter::linear);
    const half4 outColor = inputTexture.sample(quadSampler, float2(inX, inY));
    outputTexture.write(outColor, grid);
}

Harbeth功能清单

最后

✌️.

上一篇下一篇

猜你喜欢

热点阅读