ios - UIImage View 没有自动布局的整数高度,绘制的线条变得模糊

标签 ios iphone swift core-graphics cgcontext

我正在尝试为 iPhone 制作一个简单的绘图应用程序。一切正常,直到我尝试布局。

由于 iPhone 图片格式的原因,我的 Imageview 应该有一个固定的 3:4 纵横比。我还将它固定在顶部布局指南和两侧。

我画的线在扭曲,“流走”

flowing lines - screenshot

我越接近 View 的底部,线被向上拉得越多。

我在某处读到这可能是由于自动布局后 View 接收到的高度不是整数引起的,这似乎是真的:

rect measurements and autolayout constraints

我不想为每个 iOS 设备硬编码 rect。

我怎样才能“四舍五入”这个 0.5 的高度?

这是我画线的方法:

func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {

    // 1
    UIGraphicsBeginImageContext(tempImageView.frame.size)

    let context = UIGraphicsGetCurrentContext()
    tempImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: tempImageView.frame.size.width, height: tempImageView.frame.size.height))


    // 2
    CGContextMoveToPoint(context, fromPoint.x, fromPoint.y)
    CGContextAddLineToPoint(context, toPoint.x, toPoint.y)

    // 3
    CGContextSetLineCap(context, CGLineCap.Round)
    CGContextSetLineWidth(context, brushWidth)
    CGContextSetRGBStrokeColor(context, red, green, blue, 1.0)
    CGContextSetBlendMode(context, CGBlendMode.Normal)

    // 4b
    CGContextStrokePath(context)

    // 5
    tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    tempImageView.alpha = opacity
    UIGraphicsEndImageContext()

}

我已经尝试过关闭抗锯齿,但这没有用,它只会让它看起来很糟糕。

最佳答案

使用 UIGraphicsBeginImageContext 创建 Canvas 时,默认比例为 1。这可能导致生成的图像不够清晰,无法在视网膜屏幕上显示。

所以你显然需要指定比例,要么指定你想要的比例,要么指定0,让屏幕决定比例。

UIGraphicsBeginImageContextWithOptions(tempImageView.frame.size, false, 0.0)

关于ios - UIImage View 没有自动布局的整数高度,绘制的线条变得模糊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34486634/

相关文章:

ios - swift 中 UIAlertView 错误

c++ - 如何在IOS中打印xml图像?

iphone - 如何将图像放到 iPad 模拟器上

ios - 带有分组 TableView 的 UISearchBar——在 Swift 中

ios - 分段控制无需重新加载

ios - preferredStatusBarHidden 在自定义单元格和对象类中

objective-c - 沿着 UIBezierPath 将 UIImage 分成两部分

iphone - UIPasteboard 粘贴板 App iOS iPhone

iphone - 使用 UIViewController 子类自定义 iPhone 控件

swift - 如何使用 Alamofire + RxSwift 同步刷新访问 token