Apo*_*llo 2 objective-c uiview ios
有没有办法画一个带虚线边框的UIView圆圈?我想控制点之间的间距和点的大小.我尝试指定自己的模式图像,但是当我将它变成圆形时它看起来不太好:
UIView *mainCircle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
[mainCircle.layer setCornerRadius:100];
[mainCircle.layer setBorderWidth:5.0];
[mainCircle.layer setBorderColor:[[UIColor colorWithPatternImage:[UIImage imageNamed:@"dotted"]] CGColor]];
[self.view addSubview:mainCircle];
[mainCircle setCenter:self.view.center];
Run Code Online (Sandbox Code Playgroud)
我唯一要补充的是,使用当前代码,您最终可以获得如下结果:
请注意,在顶部,您会得到点的重叠.这是因为圆的圆周不能完全被点的数量整除.
你之前可以通过简单的数学运算来相对容易地解决这个问题.我写了几行代码,它们允许你提供一个点直径值,以及一个预期的点间距 - 它将尝试近似最接近的点间距,这将导致整数个点.
此外,我建议您采用100%分层方法,CAShapeLayer用于绘制圆圈.这样,您可以轻松地向其添加动画,而无需为每个帧完全重新绘制动画.
像这样的东西应该做的伎俩:
// your dot diameter.
CGFloat dotDiameter = 10.0;
// your 'expected' dot spacing. we'll try to get as closer value to this as possible.
CGFloat expDotSpacing = 20.0;
// the size of your view
CGSize s = self.view.frame.size;
// the radius of your circle, half the width or height (whichever is smaller) with the dot radius subtracted to account for stroking
CGFloat radius = (s.width < s.height) ? s.width*0.5-dotDiameter*0.5 : s.height*0.5-dotDiameter*0.5;
// the circumference of your circle
CGFloat circum = M_PI*radius*2.0;
// the number of dots to draw as given by the circumference divided by the diameter of the dot plus the expected dot spacing.
NSUInteger numberOfDots = round(circum/(dotDiameter+expDotSpacing));
// the calculated dot spacing, as given by the circumference divided by the number of dots, minus the dot diameter.
CGFloat dotSpacing = (circum/numberOfDots)-dotDiameter;
// your shape layer
CAShapeLayer* l = [CAShapeLayer layer];
l.frame = (CGRect){0, 0, s.width, s.height};
// set to the diameter of each dot
l.lineWidth = dotDiameter;
// your stroke color
l.strokeColor = [UIColor blackColor].CGColor;
// the circle path - given the center of the layer as the center and starting at the top of the arc.
UIBezierPath* p = [UIBezierPath bezierPathWithArcCenter:(CGPoint){s.width*0.5, s.height*0.5} radius:radius startAngle:-M_PI*0.5 endAngle:M_PI*1.5 clockwise:YES];
l.path = p.CGPath;
// prevent that layer from filling the area that the path occupies
l.fillColor = [UIColor clearColor].CGColor;
// round shape for your stroke
l.lineCap = kCALineCapRound;
// 0 length for the filled segment (radius calculated from the line width), dot diameter plus the dot spacing for the un-filled section
l.lineDashPattern = @[@(0), @(dotSpacing+dotDiameter)];
[self.view.layer addSublayer:l];
Run Code Online (Sandbox Code Playgroud)
您现在将获得以下输出:
如果你想在a中使用它UIView,我建议继承它并添加CAShapeLayer作为子层.您还需要添加遮罩层,以便将视图的内容遮盖到边框内.
我在下面的完整项目中添加了一个这样的例子.
完整项目:https://github.com/hamishknight/Dotted-Circle-View
| 归档时间: |
|
| 查看次数: |
2821 次 |
| 最近记录: |