Swift 在CGContext中绘制时的透明度不起作用

Swift 在CGContext中绘制时的透明度不起作用,swift,draw,alpha,cgcontext,Swift,Draw,Alpha,Cgcontext,你好,我正在开发一个绘图应用程序。我尝试在一个上下文中绘制多条具有透明度的线(一条线覆盖另一条线),但当在一个图像上绘制另一个图像时,透明度不起作用。我用两个正方形做了这个测试: var imageView:UIImageView = UIImageView() imageView.frame = CGRect(x: 0, y: 0, width: 400, height: 200) self.addSubview(imageView) /* CREATE A SQUARE UIImage *

你好,我正在开发一个绘图应用程序。我尝试在一个上下文中绘制多条具有透明度的线(一条线覆盖另一条线),但当在一个图像上绘制另一个图像时,透明度不起作用。我用两个正方形做了这个测试:

var imageView:UIImageView = UIImageView()
imageView.frame = CGRect(x: 0, y: 0, width: 400, height: 200)
self.addSubview(imageView)

/* CREATE A SQUARE UIImage */
let color:UIColor = UIColor(red:1.00, green:0.40, blue:0.21, alpha:1.0)
let bounds:CGRect = CGRect(x: 0, y: 0, width: 200, height: 200)
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
var ctx = UIGraphicsGetCurrentContext()
ctx?.setFillColor(color.cgColor)
ctx?.fill(bounds)
let rectangleUIImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()

/* DRAW SCUARE WHIT ALPHA 1 */
UIGraphicsBeginImageContextWithOptions(imageView.frame.size, false, 0.0)
ctx = UIGraphicsGetCurrentContext()
ctx?.setAlpha(1.0)
ctx?.draw(rectangleUIImage.cgImage!, in: CGRect(x: 0, y: 0, width: 200, height: 200))

/* DRAW 10 SQUARES WHIT ALPHA 0.1 IN THE SAME PLACE */
ctx?.setAlpha(0.1)
for i in 0..<10 { 
  ctx?.draw(rectangleUIImage.cgImage!, in: CGRect(x: 200, y: 0, width: 200, height: 200))
 }


imageView.image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
var-imageView:UIImageView=UIImageView()
imageView.frame=CGRect(x:0,y:0,宽度:400,高度:200)
self.addSubview(imageView)
/*创建一个正方形图像*/
let color:UIColor=UIColor(红色:1.00,绿色:0.40,蓝色:0.21,阿尔法:1.0)
让边界:CGRect=CGRect(x:0,y:0,宽度:200,高度:200)
UIGraphicsBeginImageContextWithOptions(bounds.size,false,0.0)
var ctx=UIGraphicsGetCurrentContext()
ctx?.setFillColor(color.cgColor)
ctx?填充(边界)
让rectangleUIImage:UIImage=UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsSendImageContext()
/*绘制带ALPHA 1的SCU*/
UIGraphicsBeginImageContextWithOptions(imageView.frame.size,false,0.0)
ctx=UIGraphicsGetCurrentContext()
ctx?.setAlpha(1.0)
ctx?.draw(rectangleUIImage.cgImage!,in:CGRect(x:0,y:0,宽度:200,高度:200))
/*在同一位置绘制10个ALPHA为0.1的正方形*/
ctx?.setAlpha(0.1)

对于0中的i。如果在第二次调用
UIGraphicsBeginImageContextWithOptions
后获得新上下文,可能会有所帮助。非常感谢,但我得到了相同的结果:(如果在第二次调用
UIGraphicsBeginImageContextWithOptions
后获得新上下文,可能会有所帮助。非常感谢,但我得到了相同的结果:(