新屏幕尺寸的视图中心化进度圈
问题描述:
我在我的应用程序中有一个进步圈,可用于3.5和4英寸屏幕,但是我刚开始更新我的iPhone 6和6 Plus应用程序的过程,而我已经注意到进度圈并不按照预期运作。新屏幕尺寸的视图中心化进度圈
原因是我已经硬编码了进度圈的位置,以小屏幕为中心。
我想知道是否有人能告诉我我需要做什么来转换它,以便无论屏幕大小,圆圈都居中?
这里是我的代码:
class ProgressCircle: UIView {
override func drawRect(rect: CGRect) {
var ctx = UIGraphicsGetCurrentContext()
var innerRadiusRatio: CGFloat = 0.6
var path: CGMutablePathRef = CGPathCreateMutable()
var startAngle: CGFloat = CGFloat(-M_PI_2)
var endAngle: CGFloat = CGFloat(-M_PI_2) + min(1.0, progress) * CGFloat(M_PI * 2)
var outerRadius: CGFloat = CGRectGetWidth(self.bounds) * 0.5 - 1.0
var innerRadius: CGFloat = outerRadius * innerRadiusRatio
var center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))
//Code for background circle
var context: CGContextRef = UIGraphicsGetCurrentContext()
colourTheme = NSUserDefaults.standardUserDefaults().integerForKey("themeSettings")
if colourTheme == 1 {
CGContextSetFillColorWithColor(context, (UIColorFromRGB(0xEAEAEA)).CGColor)
} else {
CGContextSetFillColorWithColor(context, (UIColor.darkGrayColor()).CGColor)
}
var rectangle: CGRect = CGRectMake(0, 0, 171, 171)
CGContextBeginPath(context)
CGContextAddEllipseInRect(context, rectangle)
CGContextDrawPath(context, kCGPathFill)
UIGraphicsEndImageContext()
if colourTheme == 1 {
CGContextSetFillColorWithColor(context, (UIColor.darkGrayColor()).CGColor)
} else {
CGContextSetFillColorWithColor(context, (UIColorFromRGB(0xEAEAEA)).CGColor)
}
var rectangleSmall: CGRect = CGRectMake(35.95, 35.95, 99.1, 99.1) //102.6
CGContextBeginPath(context)
CGContextAddEllipseInRect(context, rectangleSmall)
CGContextDrawPath(context, kCGPathFill)
UIGraphicsEndImageContext()
//Code for progress radius
CGPathAddArc(path, nil, center.x, center.y, innerRadius, startAngle, endAngle, false)
CGPathAddArc(path, nil, center.x, center.y, outerRadius, endAngle, startAngle, true)
CGPathCloseSubpath(path)
CGContextAddPath(ctx, path)
CGContextSaveGState(ctx)
CGContextClip(ctx)
if percent > 100 {
CGContextDrawImage(ctx, self.bounds, UIImage(named: "RadialProgressFillOver").CGImage)
} else {
CGContextDrawImage(ctx, self.bounds, UIImage(named: "RadialProgressFill").CGImage)
}
CGContextRestoreGState(ctx)
}
答
想通了。这实际上很明显,但我忘记了实际上将进度圈添加到视图的方式。
这里是我想出了解决方案:
var circleFrame = CGRect(x: (budgetDisplayView.bounds.width/2)-85.5, y: 249, width: 171, height: 171)
var circle = ProgressCircle(frame: circleFrame)
self.budgetDisplayView.addSubview(circle)
self.budgetDisplayView.sendSubviewToBack(circle)
通过IB
简单的用自动版式。你是否决定以编程的方式来做这件事? – davidrayowens 2014-10-04 21:57:41
你如何把这个观点放在屏幕上? – rdelmar 2014-10-04 21:59:38
@dvdowns是的,我试过使用AutoLayout,我真的不喜欢它。我的应用中没有很多元素是这样的,所以我决定使用单独的故事板会是更好的解决方案。 – user3746428 2014-10-04 22:10:49