如何在Swift中防止对图像的特定区域进行着色?

huangapple go评论150阅读模式
英文:

how to prevent coloring a specific area of an image in Swift?

问题

我正在学习在iOS中使用CoreImage和Vision库来实现一个涂色应用程序。该应用程序向用户展示了一个带有白色背景和黑色边缘的素描,用户可以对其进行涂色,就像这张图片一样:如何在Swift中防止对图像的特定区域进行着色?

我可以使用Canvas来给视图上色,并指定线宽和颜色。然而,面临的挑战是:

1- 如何防止用户给原始图像中的黑色线条上色?

2- 如果用户用黑色涂色了特定区域,如何允许用户修改该区域(擦除黑色或在该区域上覆盖不同颜色),同时防止用户给原始图像中的黑线上色?

3- 如果用户可以从一组素描中选择一个素描,每个素描都有独特的宽度和高度,我应该采取哪种最佳方法来实现问题1中的要求?

我按照这个教程来检测黑色线条,使用轮廓检测:轮廓检测教程

由于我的代码太长,我正在使用pastern.com:
源代码

英文:

I'm learning CoreImage and Vision libraries in iOS by implementing a coloring app. The app shows a sketch with white background and black edges to the user to color, such as this image: 如何在Swift中防止对图像的特定区域进行着色?

I can color a view using Canvas and specify the line width and color. However, the challenges are:

1- how can I prevent the user from coloring those black lines in the original image?

2-if the user colors a specific area with black color, how can I allow the user to modify that area (erase the black color, or over the color of that area with a different color) while preventing the user from coloring the black lines in the original image?

3- if the user can select a sketch from a set of sketches and each sketch has a unique width and height, what is the best approach I should take to achieve the point in question number 1?

I followed this tutorial to detect the black line using contour detection: contour detection tutorial

because my code is too long, I'm using pastern.com:
source code

答案1

得分: 1

将模板(老虎)和用户绘制的画布分为两个不同的图像,以便模板图像永远不会被直接修改。

然后使用“multiply”混合模式将用户的绘画与模板图像混合在一起。这样,模板中的黑色区域(轮廓线)在结果图像中仍然保持黑色(黑色 = 0,所以someColor * 0 = 0(黑色)),白色部分将显示用户的颜色(白色 = 1,someColor * 1 = someColor)。

SwiftUI有一个.blendMode(.multiply)修饰符,可能适合您的用例。

通过将用户的绘画与模板分开,还确保用户在擦除绘画部分时不会擦除模板图像。

英文:

Conceptually, you could do the following:

Separate the template (the tiger) and the canvas the user draws on into two different images, so that the template image is never modified directly.

Then blend the user's drawing over the template image using the multiply blend mode. This way, any area that is black in the template (the contour lines) will stay black in the result image (black = 0, so someColor * 0 = 0 (black)), and the white part will show the user's color (white = 1, someColor * 1 = someColor).

SwiftUI has a .blendMode(.multiply) modifier that might do the trick for your use case.

By separating the user's drawing from the template, you also ensure that when the user erases parts in their drawing, they don't erase the template image.

huangapple
  • 本文由 发表于 2023年7月4日 23:23:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76614027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定