如何将UIImageView裁剪为自定义形状 [英] How to crop a UIImageView to a custom shape

查看:42
本文介绍了如何将UIImageView裁剪为自定义形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户是否可以在希望裁剪的 UIImageView 的位周围绘制一条虚线(以圆圈为单位),然后为 UIImageView 调整到这些点?有点像Photoshop中的套索/选取框效果:

Is it possible for a user to draw a dotted line (in a circle) around the bit of the UIImageView they wish to crop to, and then for the UIImageView to resize to those points? It's a bit like the lasso/marquee effect in Photoshop:

推荐答案

更新:自iOS 8.x起,UIImageView提供了 maskView 属性.只需准备具有一些不透明像素的图像,使用该蒙版图像创建另一个图像视图,然后将此蒙版图像视图设置为maskView.遮罩图像中的不透明像素将是基础图像中显示的像素.

Update: Since iOS 8.x, UIImageView provides a maskView property. Just prepare an image with some opaque pixels, create another image view with that mask image, and set this mask image view as the maskView. The opaque pixels in the mask image will be the ones shown in the underlying image.

    UIImageView *maskView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"somemask"]];
    maskView.frame = imageView.bounds;
    imageView.maskView = maskView;
    // imageView will be masked by maskView

.

原始答案

有很多事情要做,但这是一个高层次的概述:

There's quite a bit to do, but here's a high-level outline:

  1. 创建一个将成为遮罩的空图像
  2. 根据用户输入在该图像中构建路径
  3. 填写将其转换为蒙版的路径
  4. 将遮罩应用于imageview的图像

创建图像:这里的一个简单想法是在项目中附带一个黑色图像.它的大小应匹配用户可以选择的最大区域.将图像读取到内存中( UIImage imageNamed:),并通过调用 UIGraphicsBeginImageContext 将其设置为绘图上下文.

Create image: A simple idea here is to just ship a black image with your project. It should be sized to match the maximum region a user can select. Read the image into memory (UIImage imageNamed:) and set it up as the drawing context by calling UIGraphicsBeginImageContext.

创建路径:(参见苹果文档).当用户开始抚摸区域时,调用 CGContextBeginPath ,然后跟随用户手势,对触摸进行采样并通过作为touchesMoved反复调用 CGContextMoveToPoint 来添加小段.

Create path: (see apple docs). When the user starts stroking the region, call CGContextBeginPath, then follow user gestures, sampling the touches and adding small segments by calling CGContextMoveToPoint repeatedly as touchesMoved.

创建蒙版:要将路径转换为蒙版,您需要黑色背景,并且路径要用白色填充.如果从黑色图像开始,则只需要进行填充即可.请参阅相同的苹果指南.

Create mask: To turn the path into a mask you want a black background and the path filled with white. If you started with a black image, you just need to do the fill. See the same apple guide about doing that.

最后,您将此蒙版应用于imageView的图像.这里是不错的参考书.

Finally, you'll apply this mask to your imageView's image. Here's a decent reference for that.

这篇关于如何将UIImageView裁剪为自定义形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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