SwiftUI路径为contentShape,与Image不对齐 [英] SwiftUI Path as contentShape, doesn't line up with Image

查看:100
本文介绍了SwiftUI路径为contentShape,与Image不对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL; DR :我正在使用Path指定Image的匹配区域.但是我不知道如何调整Path坐标以匹配SwiftUI决定的布局...或者甚至不需要这样做.

TL;DR: I'm using a Path to specify the hit area for an Image. But I don't know how to adjust the Path coordinates to match the layout that SwiftUI decides on... or if I even need to do so.

运行时

我的(测试)应用看起来像这样,为清晰起见,Image边框(不是框架)已上色:

My (test) app looks like this, Image borders (not frames) colored for clarity:

想要的目的是让不透明的橙色水龙头由该Image处理.即使在橙色图像的边界内,不透明橙色以外的水龙头也应掉入"绿色图像或灰色背景.但不是. (紫色轮廓根据其自身显示了路径的位置;请参见下面的代码.)

What I want is for taps in the opaque orange to be handled by that Image. Taps outside the opaque orange — even if within the bounds of the orange image — should "fall through" either to the green image or the gray background. But no. (The purple outline shows where the path is, according to itself; see code below).

详细信息

这是图像的固有(以像素为单位)布局:

Here's the intrinsic (in pixels) layout of the images:

不透明部分周围的路径被视为

The path around the opaque part is trivially seen to be

[(200, 200), (600, 200), (600, 600), (200, 600)] 

这些坐标和Image坐标如何关联?

How do these coordinates and the Image coordinates relate?

代码

extension CGPoint {
    typealias Tuple = (x:CGFloat, y:CGFloat)
    init(tuple t: Tuple) {
        self.init(x: t.x, y: t.y)
    }
}

struct ContentView: View {

    var points = [(200, 200), (600, 200), (600, 600), (200, 600)]
        .map(CGPoint.init(tuple:))
        // .map { p in p.shifted(dx:-64, dy:-10)}  // Didn't seem to help.

    var path : Path {
        var result = Path()
        result.move(to: points.first!)
        result.addLines(points)
        result.closeSubpath()
        return result
    }

    var body: some View {
        ZStack{
            Image("gray")       // Just so we record all touches.
            .resizable()
            .frame(maxWidth : .infinity,maxHeight: .infinity)
            .onTapGesture {
                print("background")
            }

            Image("square_green")
            .resizable()
            .scaledToFit()
            .border(Color.green, width: 4)
            .offset(x: 64, y:10)    // So the two Images don't overlap completely.
            .onTapGesture {
                print("green")
            }

            Image("square_orange")
            .resizable()
            .scaledToFit()
            .contentShape(path)        // Magic should happen here.
            .border(Color.orange, width: 4)
            .offset(x: -64, y:-10)
            // .contentShape(path)     // Didn't work here either.
            .onTapGesture {
                 print("orange")
            }

            path.stroke(Color.purple)  // Origin at absolute (200,200) as expected.

        }
    }
}

推荐答案

阿斯佩里(Asperi)是正确的,当我读到保罗·哈德森(Paul Hudson),并掌握了Shape的(单个)要求-路径( in rect:CGRect ) ->路径方法. rect参数告诉您有关局部坐标系的所有信息,即其大小.

Asperi was correct, and it dawned on me when I read Paul Hudson and grasped the (single) requirement of Shape — a path(in rect: CGRect) -> Path method. The rect parameter tells you all you need to know about the local coordinate system: namely, its size.

我的工作代码现在看起来像这样.

My working code now looks like this.

助手

extension CGPoint {
    func scaled(xFactor:CGFloat, yFactor:CGFloat) -> CGPoint {
        return CGPoint(x: x * xFactor, y: y * yFactor)
    }

    typealias SelfMap = (CGPoint) -> CGPoint
    static func scale(_ designSize: CGSize, into displaySize: CGSize) -> SelfMap {{
        $0.scaled(
            xFactor: displaySize.width  / designSize.width,
            yFactor: displaySize.height / designSize.height
        )
    }}

    typealias Tuple = (x:CGFloat, y:CGFloat)
    init(tuple t: Tuple) {
        self.init(x: t.x, y: t.y)
    }
}

在适当的背景下绘制路径

// This is just the ad-hoc solution. 
// You will want to parameterize the designSize and points.

let designSize = CGSize(width:800, height:800)
let opaqueBorder = [(200, 200), (600, 200), (600, 600), (200, 600)]

// To find boundary of real-life images, see Python code below.

struct Mask : Shape {
    func path(in rect: CGRect) -> Path {
        let points = opaqueBorder
            .map(CGPoint.init(tuple:))

            // *** Here we use the context *** (rect.size)
            .map(CGPoint.scale(designSize, into:rect.size))

        var result = Path()
        result.move(to: points.first!)
        result.addLines(points)
        result.closeSubpath()
        return result
    }
}

使用面具

struct ContentView: View {
    var body: some View {
        ZStack{
            Image("gray")           // Just so we record all touches.
            .resizable()
            .frame(
                maxWidth : .infinity,
                maxHeight: .infinity
            )
            .onTapGesture {
                    print("background")
            }

            // Adding mask here left as exercise.
            Image("square_green")
            .resizable()
            .scaledToFit()
            .border(Color.green, width: 4)
            .offset(x: 64, y:10)    // So the two Images don't overlap completely.
            .onTapGesture {
                print("green")
            }

            Image("square_orange")
            .resizable()
            .scaledToFit()
            .border(Color.orange, width: 4)

           // Sanity check shows the Mask outline.
            .overlay(Mask().stroke(Color.purple))

            // *** Actual working Mask ***
            .contentShape(Mask())

            .offset(x: -64, y:-10)
            .onTapGesture {
                print("orange")
            } 
        }
    }
}

获取大纲

#!/usr/bin/python3

# From https://www.reddit.com/r/Python/comments/f2kv1/question_on_tracing_an_image_in_python_with_pil

import sys
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame

# Find simple border.

fname   = sys.argv[1]
image   = pygame.image.load(fname)
bitmask = pygame.mask.from_surface(image) 
comp    = bitmask.connected_component() 
outline = comp.outline(48)

print("name:  ", fname)
print("size:  ", image.get_rect().size)
print("points:", outline)

# Sanity check.
# From https://www.geeksforgeeks.org/python-pil-imagedraw-draw-polygon-method

from PIL import Image, ImageDraw, ImagePath
import math

box = ImagePath.Path(outline).getbbox()
bsize = list(map(int, map(math.ceil, box[2:])))

im = Image.new("RGB", bsize, "white")
draw = ImageDraw.Draw(im)
draw.polygon(outline, fill="#e0c0ff", outline="purple")

im.show()      # That this works is amazing.

这篇关于SwiftUI路径为contentShape,与Image不对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆