【发布时间】:2017-08-25 13:21:35
【问题描述】:
我有一个 UICollectionView 可以显示圆形、椭圆形、长方形等形状。因此,当我单击 Cell 时,我需要在 UIView 上绘制相同的形状,然后我需要移动并调整通过单击 Cell 绘制的视图的大小。它如何在 iOS 中实现?提前致谢。
【问题讨论】:
标签: ios objective-c iphone uiimage core-graphics
我有一个 UICollectionView 可以显示圆形、椭圆形、长方形等形状。因此,当我单击 Cell 时,我需要在 UIView 上绘制相同的形状,然后我需要移动并调整通过单击 Cell 绘制的视图的大小。它如何在 iOS 中实现?提前致谢。
【问题讨论】:
标签: ios objective-c iphone uiimage core-graphics
如果您使用 UICollectionView,您的可重用单元格将有“层”可供绘制。
怎么办?
1.创建一个UIView 子类并将其放置在您的可重用单元格中。
2. 覆盖drawRect(_:) 方法,您将完成里面的所有绘图。
3. 将您的shape/line drawing code 添加到drawRect 方法。
例如,将UIBezierPath 类用于线条、弧线等。您将能够创建各种形状。
您应该阅读 CoreGraphics API 参考:
https://developer.apple.com/reference/coregraphics
还可以了解Layers、Contexts 和drawRect:
circle 的一个非常基本的示例:
class CircleView: UIView {
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
context.addEllipse(in: rect)
context.setFillColor(.red.cgColor)
context.fillPath()
}
}
并使用 UIBezier 路径绘制线条(矩形、星形等):
override func drawRect(rect: CGRect) {
var path = UIBezierPath()
path.moveToPoint(CGPoint(x:<point x>, y:<point y>))
path.addLineToPoint(CGPoint(x:<next point x>, y:<next point y>))
point.closePath()
UIColor.redColor().set()
point.stroke()
point.fill()
}
【讨论】:
研究贝塞尔路径。这是可能的。希望它对你有用。
【讨论】:
您可以使用 CAShapeLayer。例如。画一个圆圈。
shapeLayer = [CAShapeLayer layer];
shapeLayer.frame = aFrame;
UIBezierPath *spath = [UIBezierPath bezierPathWithArcCenter:centerPoint radius:12 startAngle:0 endAngle:(2 * M_PI) clockwise:YES];
shapeLayer.strokeColor = [UIColor colorWithRed:71/255.0 green:157/255.0 blue:252/255.0 alpha:1].CGColor;
shapeLayer.path = spath.CGPath;
shapeLayer.strokeStart = 0;
shapeLayer.strokeEnd = 0;
shapeLayer.fillColor = nil;
shapeLayer.lineWidth = 2;
[self.layer addSublayer:shapeLayer];
希望对你有帮助
【讨论】:
UICollectionView
您可以使用图层的属性:
【讨论】: