UIImage视图没有带autolayout的整数高度,绘制的线条变得模糊

时间:2015-12-28 01:19:29

标签: ios iphone swift core-graphics cgcontext

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

由于iPhone图片格式,我的Imageview应该具有3:4的固定宽高比。我还将它固定在顶部布局指南和侧面。

我绘制的线条被扭曲,并且#34;流走了#34;

flowing lines - screenshot

越接近视图的底端,线越向上拉。

我在某处看到它可能是由于视图在自动布局后接收到的高度不是整数,这似乎是真的:

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()

}

我已经尝试过切换防眩光,但这并没有帮助,只是让它看起来很糟糕。

1 个答案:

答案 0 :(得分:3)

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

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

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