我有一个collectionView,显示CardCells中带有CardLayout的不同卡片。
每个细胞应显示某种颜色的形状。它永远不应该显示多种颜色。
当我向下滚动时向上滚动,我看到多个颜色重叠。我想这是因为出队了。我尝试在clear:frame
和CGContext
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let c = collectionView.dequeueReusableCell(withReuseIdentifier: "card", for: indexPath) as! CardCell
c.card = deck.active[indexPath.row]
c.cardLayout = cardLayout
c.setNeedsDisplay()
return c
}
class CardCell: UICollectionViewCell {
var card = Card()
var cardLayout = CardLayout()
override init(frame: CGRect) {
super.init(frame: frame)
layer.borderColor = UIColor.white.cgColor
layer.borderWidth = 2
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func getCenter() -> CGPoint {
return CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
}
override func draw(_ rect: CGRect) {
let c = UIGraphicsGetCurrentContext();
cardLayout.render(c: c!, card: card, frame: frame)
}
}
class CardLayout: NSObject {
func color(i: Int) -> UIColor {
return [1: UIColor.red, 2: UIColor.green, 4: UIColor.blue][i]!
}
func getCenter(frame: CGRect) -> CGPoint {
return CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
}
func quantity(i: Int) -> Int {
return [1: 1, 2: 2, 4: 3][i]!
}
func loadPath(c: CGContext, card: Card) {
if card.fill == 1 {
c.setFillColor(color(i: card.color).cgColor)
} else {
c.setStrokeColor(color(i: card.color).cgColor)
}
}
func drawPath(c: CGContext, card: Card) {
if card.fill == 1 {
c.fillPath()
} else {
c.strokePath()
}
}
func render1(c: CGContext, card: Card, frame: CGRect, y: CGFloat) {
c.addArc(center: CGPoint(x: frame.size.width / 2, y: y) , radius: frame.size.width / 10, startAngle: 0, endAngle: 360 * 3.142 / 180, clockwise: true)
}
func render2(c: CGContext, card: Card, frame: CGRect, y: CGFloat) {
let m = frame.size.width / 2
let size = CGFloat(10)
c.move(to: CGPoint(x: m, y: y - size))
c.addLine(to: CGPoint(x: m - size, y: y + size))
c.addLine(to: CGPoint(x: m + size, y: y + size))
c.addLine(to: CGPoint(x: m, y: y - size))
}
func render3(c: CGContext, card: Card, frame: CGRect, y: CGFloat) {
}
func render(c: CGContext, card: Card, frame: CGRect) {
let size = frame.size.height / 6
var num = quantity(i: card.quantity)
var sy = size
if num == 1 {
sy = frame.size.height / 2
} else if num == 2 {
sy = (frame.size.height / 2) - (size * 0.5)
} else if num == 3 {
sy = (frame.size.height / 2) - size
}
while num > 0 {
c.beginPath()
c.addRect(frame)
c.setFillColor(UIColor.black.cgColor)
c.fillPath()
c.beginPath()
loadPath(c: c, card: card)
if card.shape == 1 {
render1(c: c, card: card, frame: frame, y: sy)
} else if card.shape == 2 {
render2(c: c, card: card, frame: frame, y: sy)
} else if card.shape == 3 {
// render3(c: c, card: card, frame: frame, y: sy)
}
drawPath(c: c, card: card)
num = num - 1
sy = sy + size
}
}
}
的矩形上绘画,两者都没有(明显的)效果。
#!r5rs