草庐IT

ios - UIDragInteractionDelegate : How to display transparent parts in the drag preview returned by dragInteraction(_:previewForLifting:session:)

coder 2023-09-24 原文

我正在构建一个 drag and drop iOS 应用程序的交互。我想让用户能够拖放包含透明部分的图像。

但是,拖动内容的默认预览是一个具有不透明白色背景的矩形,覆盖了我的应用程序的背景。

当我通过实现 UIDragInteractionDelegate 方法创建自定义预览时 dragInteraction(_:previewForLifting:session:) ,如 Apple 的代码示例中所示 Adopting Drag and Drop in a Custom View ,我的源图像的透明度仍然没有被考虑在内,这意味着我的预览图像仍然显示在一个具有不透明白色背景的矩形中:

func dragInteraction(_ interaction: UIDragInteraction, previewForLifting item: UIDragItem, session: UIDragSession) -> UITargetedDragPreview? {
    guard let image = item.localObject as? UIImage else { return nil }

    // Scale the preview image view frame to the image's size.
    let frame: CGRect
    if image.size.width > image.size.height {
        let multiplier = imageView.frame.width / image.size.width
        frame = CGRect(x: 0, y: 0, width: imageView.frame.width, height: image.size.height * multiplier)
    } else {
        let multiplier = imageView.frame.height / image.size.height
        frame = CGRect(x: 0, y: 0, width: image.size.width * multiplier, height: imageView.frame.height)
    }

    // Create a new view to display the image as a drag preview.
    let previewImageView = UIImageView(image: image)
    previewImageView.contentMode = .scaleAspectFit
    previewImageView.frame = frame

    /*
         Provide a custom targeted drag preview that lifts from the center
         of imageView. The center is calculated because it needs to be in
         the coordinate system of imageView. Using imageView.center returns
         a point that is in the coordinate system of imageView's superview,
         which is not what is needed here.
     */
    let center = CGPoint(x: imageView.bounds.midX, y: imageView.bounds.midY)
    let target = UIDragPreviewTarget(container: imageView, center: center)
    return UITargetedDragPreview(view: previewImageView, parameters: UIDragPreviewParameters(), target: target)
}

我试图强制预览不透明,但没有帮助:

previewImageView.isOpaque = false

如何在电梯预览中获得透明部分?

最佳答案

覆盖backgroundColorUIDragPreviewParameters ,因为它定义了拖动项目预览的背景颜色

设置为UIColor.clear这是一个灰度和 alpha 值都为 0.0 的颜色对象

let previewParameters = UIDragPreviewParameters()
previewParameters.backgroundColor = UIColor.clear // transparent background
return UITargetedDragPreview(view: previewImageView,
                             parameters: previewParameters,
                             target: target)

关于ios - UIDragInteractionDelegate : How to display transparent parts in the drag preview returned by dragInteraction(_:previewForLifting:session:),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47096983/

有关ios - UIDragInteractionDelegate : How to display transparent parts in the drag preview returned by dragInteraction(_:previewForLifting:session:)的更多相关文章

随机推荐