如何将蒙版对齐到图像上

时间:2014-12-31 00:26:03

标签: swift uiimage calayer masking

我在Swift写作,试图使用UIImage和CALayer来掩盖图像。问题是当应用于图像时,掩模被缩放和移位。我使用Interface Builder创建了我的UIImageViewer,并将其设置为Aspect Fit。我想掩盖任意大小的图像。我生成的蒙版图像与图像的大小相同。这是一个要求,因为稍后我想以编程方式向我的蒙版添加更多元素,它必须覆盖蒙版图像。这是我的代码:

class ViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    var img = UIImage(named: "flowers.png")

    var maskImageSize = CGSizeMake(img!.size.width, img!.size.height)

    UIGraphicsBeginImageContextWithOptions(maskImageSize, false, 0.0)

    var color = UIColor(white: 1.0, alpha: 0.0)
    color.setFill()
    var rect = CGRectMake(0, 0, img!.size.width, img!.size.height)
    UIRectFill(rect)

    color = UIColor(white: 0.0, alpha: 1.0)
    color.setFill()
    rect = CGRectMake((img!.size.width/2)-50, (img!.size.height/2)-50, 100, 100)
    UIRectFill(rect)

    var maskImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    var maskLayer = CALayer()
    maskLayer.frame = self.imageView.layer.bounds // it'll have the same problem if I set it to self.imageView.layer.frame
    maskLayer.contents = maskImage.CGImage
    maskLayer.contentsGravity = kCAGravityCenter

    self.imageView.image = img
    self.imageView.layer.mask = maskLayer;
    self.imageView.layer.masksToBounds = true
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

我需要知道如何将图像蒙版对齐到原始图像上。谢谢你的帮助!

我有很好的屏幕截图,但Stackoverflow不允许我发布它们,因为我没有足够的声誉!

2 个答案:

答案 0 :(得分:1)

这里的问题是,如果使用宽高比,则显示的图像大小取决于原始图像的大小和图像视图的大小。你要做的是模仿图像视图对图像的作用 - 你无法确切知道它是什么。

你能做的最好的就是猜测。你要找的是最大矩形的大小,它将适合你的图像视图的边界,同时保持原始图像的纵横比。碰巧的是,如果您导入AV Foundation框架,那么有一个方便的功能可以为您提供这些信息AVMakeRectWithAspectRatioInsideRect(此处记录为:https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVFoundation_Functions/index.html#//apple_ref/c/func/AVMakeRectWithAspectRatioInsideRect)。

答案 1 :(得分:0)

我也遇到了同样的问题,我在UIImageView的实用程序中修复了它。在绘图部分中,我只需查看剪辑子视图 像这样 clipSubview of the UIImageView

问题已解决!

相关问题