我试图在Cocoa Touch的UIView的底部边缘下画一个阴影。我知道我应该使用CGContextSetShadow()来绘制阴影,但Quartz 2D编程指南有点模糊:
保存图形状态。
调用CGContextSetShadow函数,传递适当的值。
执行要应用阴影的所有绘图。
恢复图形状态
我已经尝试了以下在一个UIView子类:
- (void)drawRect:(CGRect)rect {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(currentContext);
CGContextSetShadow(currentContext, CGSizeMake(-15, 20), 5);
CGContextRestoreGState(currentContext);
[super drawRect: rect];
}
..但是这对我来说不工作,我有点卡住了(a)下一步要去哪里(b)如果我需要对我的UIView做什么来让这个工作?
对萨玛里人来说,萨玛里人。iOS/ c#版本的答案如下所示:
public override void DrawRect(CGRect area, UIViewPrintFormatter formatter)
{
CGContext currentContext = UIGraphics.GetCurrentContext();
currentContext.SaveState();
currentContext.SetShadow(new CGSize(-15, 20), 5);
base.DrawRect(area, formatter);
currentContext.RestoreState();
}
主要的区别是您获得CGContext的实例,您可以直接在该实例上调用适当的方法。
你可以使用这个扩展来添加阴影
extension UIView {
func addShadow(offset: CGSize, color: UIColor, radius: CGFloat, opacity: Float)
{
layer.masksToBounds = false
layer.shadowOffset = offset
layer.shadowColor = color.cgColor
layer.shadowRadius = radius
layer.shadowOpacity = opacity
let backgroundCGColor = backgroundColor?.cgColor
backgroundColor = nil
layer.backgroundColor = backgroundCGColor
}
}
你可以称之为
your_Custom_View.addShadow(offset: CGSize(width: 0, height: 1), color: UIColor.black, radius: 2.0, opacity: 1.0)
对萨玛里人来说,萨玛里人。iOS/ c#版本的答案如下所示:
public override void DrawRect(CGRect area, UIViewPrintFormatter formatter)
{
CGContext currentContext = UIGraphics.GetCurrentContext();
currentContext.SaveState();
currentContext.SetShadow(new CGSize(-15, 20), 5);
base.DrawRect(area, formatter);
currentContext.RestoreState();
}
主要的区别是您获得CGContext的实例,您可以直接在该实例上调用适当的方法。