UIImageView上的渐变

时间:2016-10-31 20:52:09

标签: ios swift uiimageview swift3 gradient

我一直试图用渐变图层填充图片视图,但我似乎无法使其工作,我尝试创建CAGradientLayer,在其上应用2种颜色然后将其应用为蒙版到主图像层。

let gradient = CAGradientLayer()
gradient.frame = (self.imageView?.bounds)!
gradient.colors = [UIColor.blue.cgColor, UIColor.purple.cgColor]
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 0.5, y: 1.0)
gradient.locations = [0, 1]
self.imageView?.layer.mask = gradient

这就是我所拥有的,这就是我想要的结果:

First Second

更新: 找到了解决方案here

2 个答案:

答案 0 :(得分:0)

您可以这样做:

---
title: "Side by Side"
date: "October 31, 2016"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

## Side by Side

\begin{minipage}{0.3\textwidth}
```{r}
knitr::kable(diag(2), format = "latex")
```
\end{minipage}
\begin{minipage}{0.3\textwidth}
```{r}
knitr::kable(diag(3), format = "latex")
```
\end{minipage}
\begin{minipage}{0.3\textwidth}
```{r echo=FALSE}
knitr::kable(diag(4), format = "latex")
```
\end{minipage}

答案 1 :(得分:0)

我得到了this的答案。添加UIImage的扩展名,只需传递颜色列表即可应用渐变。

import UIKit

extension UIImage {

func tintedWithLinearGradientColors(colorsArr: [CGColor]) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
    guard let context = UIGraphicsGetCurrentContext() else {
        return UIImage()
    }
    context.translateBy(x: 0, y: self.size.height)
    context.scaleBy(x: 1, y: -1)

    context.setBlendMode(.normal)
    let rect = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)

    // Create gradient
    let colors = colorsArr as CFArray
    let space = CGColorSpaceCreateDeviceRGB()
    let gradient = CGGradient(colorsSpace: space, colors: colors, locations: nil)

    // Apply gradient
    context.clip(to: rect, mask: self.cgImage!)
    context.drawLinearGradient(gradient!, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: self.size.height), options: .drawsAfterEndLocation)
    let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return gradientImage!
}
}