【问题标题】:Swift: draw image and border using UIGraphicsBeginImageContextWithOptionsSwift:使用 UIGraphicsBeginImageContextWithOptions 绘制图像和边框
【发布时间】:2017-01-18 08:57:18
【问题描述】:

我需要画这样的图像

提供的是:带有向下箭头图像的绿色气泡(绿色气泡图像已经有边框,所以我不需要绘制它)和中心照片。我需要在照片周围画白色边框+圆角 这是我到目前为止的代码:

let rect = CGRect(origin: .zero, size: CGSize(width: 60, height: 67))
    let width = CGFloat(50)
    let borderWidth: CGFloat = 1.0

    let imageRect = CGRect(x: 5, y: 5, width: width, height: width)
    let bubbleImg = #imageLiteral(resourceName: "pinGreen")

    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)

    let context = UIGraphicsGetCurrentContext()

    bubbleImg.draw(in: rect)

    let path = UIBezierPath(roundedRect: imageRect.insetBy(dx: borderWidth / 2, dy: borderWidth / 2), cornerRadius: width/2)
    context!.saveGState()
    path.addClip()

    image.draw(in: imageRect)
    context!.restoreGState()

    UIColor.purple.setStroke()
    path.lineWidth = borderWidth
    path.stroke()

    let roundedImage = UIGraphicsGetImageFromCurrentImageContext();
    let img = roundedImage?.cgImage!
    UIGraphicsEndImageContext();

这就是结果

谁能帮我解决这个问题? 有没有办法从 xib 文件中设计和获取这种类型的图像?

【问题讨论】:

    标签: swift core-graphics draw uigraphicscontext


    【解决方案1】:

    我会告诉你最简单的方法:

    1. 绿色气泡图像需要 imageView1,照片需要 imageView2(宽度=高度)。它们的中心是相同的。

    2. imageView2 的角半径等于其帧宽度/2。

    3. 设置imageView2层的边框颜色为白色,边框宽度约为5px。不要忘记设置maskToBounds=true

    请尝试。


    DaijDjan:这个答案在一张图片中(显示 IB + 代码 + 应用程序):

    【讨论】:

    • 可能——你应该/需要用 UIGraphics 来绘制它。你的问题很具体;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2017-10-31
    • 1970-01-01
    • 2016-06-07
    • 2018-11-26
    • 1970-01-01
    • 2021-08-30
    相关资源
    最近更新 更多