Un po 'di miglioramento per altre risposte, grazie a Ashok R per il codice swift.
Poiché stavamo creando una vista triangolare sullo sfondo della vista con l'ombra su tutti i lati e un triangolo bianco sui lati non è necessario.
Si interrompe in caso di viste con larghezza comparativamente maggiore di altezza.
Una soluzione sarà spostare il percorso per la riga dove ombra senza un po 'verso quel lato di vista, invece di creare completamente vista Path triangolare.
ho creato un'estensione per questo -
extension UIView {
func addshadow(top: Bool,
left: Bool,
bottom: Bool,
right: Bool,
shadowRadius: CGFloat = 2.0) {
self.layer.masksToBounds = false
self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
self.layer.shadowRadius = shadowRadius
self.layer.shadowOpacity = 1.0
let path = UIBezierPath()
var x: CGFloat = 0
var y: CGFloat = 0
var viewWidth = self.frame.width
var viewHeight = self.frame.height
// here x, y, viewWidth, and viewHeight can be changed in
// order to play around with the shadow paths.
if (!top) {
y+=(shadowRadius+1)
}
if (!bottom) {
viewHeight-=(shadowRadius+1)
}
if (!left) {
x+=(shadowRadius+1)
}
if (!right) {
viewWidth-=(shadowRadius+1)
}
// selecting top most point
path.move(to: CGPoint(x: x, y: y))
// Move to the Bottom Left Corner, this will cover left edges
/*
|☐
*/
path.addLine(to: CGPoint(x: x, y: viewHeight))
// Move to the Bottom Right Corner, this will cover bottom edge
/*
☐
-
*/
path.addLine(to: CGPoint(x: viewWidth, y: viewHeight))
// Move to the Top Right Corner, this will cover right edge
/*
☐|
*/
path.addLine(to: CGPoint(x: viewWidth, y: y))
// Move back to the initial point, this will cover the top edge
/*
_
☐
*/
path.close()
self.layer.shadowPath = path.cgPath
}
e impostare il valore booleano vero per qualunque lato si vuole l'ombra appaia
myView.addshadow(top: false, left: true, bottom: true, right: true, shadowRadius: 2.0)
// raggio ombra è facoltativo sopra ed è impostato come predefinito su 2.0
o myView.addshadow(top: true, left: true, bottom: true, right: true, shadowRadius: 2.0)
o myView.addshadow(top: false, left: false, bottom: true, right: true, shadowRadius: 2.0)
Questo non funziona con grande 'shadowRadius' come si può sanguinare fuori area triangolare creata con il' shadowPath '. –
È vero, puoi regolare il percorso in modo che sia un po 'più breve del resto del quadrato in quei modelli. –