Blog

iOS - Ein schneller Weg, um einen Schatten auf einer beliebigen Ansicht zu erzeugen

Jeroen Leenarts

Aktualisiert Oktober 22, 2025
2 Minuten
Manchmal möchten Sie einen Schatten auf einer Ansicht haben. Am einfachsten und schnellsten geht es, wenn Sie ihn einfach auf der Ebene der Ansicht hinzufügen: [sourcecode language="c"] -(void)loadView { CGRect frame = [[UIScreen mainScreen] applicationFrame]; self.view = [[UIView alloc] initWithFrame:frame]; self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; self.view.backgroundColor = [UIColor blackColor]; UIView *glowView = [[UIView alloc] initWithFrame:CGRectMake(frame.size.width /2 -10, frame.size.height /2 -30, 20, 60)]; glowView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin; glowView.backgroundColor = [UIColor whiteColor]; [self.view addSubview:glowView]; //Einstellen des Schattens auf dem CALayer der Ansicht. CALayer *viewLayer = glowView.layer; viewLayer.shadowOffset = CGSizeMake(0, 0); viewLayer.shadowColor = [[UIColor yellowColor] CGColor]; viewLayer.shadowPath = [UIBezierPath bezierPathWithRect:glowView.bounds].CGPath; viewLayer.shadowRadius = 10.0f; viewLayer.shadowOpacity = 1.0f; / /Lassen Sie uns das Ganze animieren, wenn wir schon dabei sind. CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"shadowOpacity"]; animation.duration = 0.5f; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; animation.fromValue = [NSNumber numberWithFloat:1.0]; animation.toValue = [NSNumber numberWithFloat:0.0]; animation.autoreverses = YES; animation.repeatCount = HUGE_VALF; [viewLayer addAnimation:animation forKey:@"shadowOpacity"]; } [/sourcecode] Ich muss zugeben, dass dies ziemlich grundlegendes Zeug ist. Aber es scheint, dass viele Leute vergessen, dass alle UIView-Unterklassen auf Core Animation CALayers basieren. Sehen Sie sich den Quellcode https://github.com/xebia/ios-DemoForBlog an und probieren Sie das Beispiel aus. Das Interessante an diesem Beispiel ist alles im vierten Tab der Anwendung enthalten, es ist der XSDFourthViewController im Code.

Verfasst von

Jeroen Leenarts

Contact

Let’s discuss how we can support your journey.