125

私のアプリケーションでは、次のような名前の4つのボタンがあります。

  • 左上
  • 左下の
  • 右上
  • 右下

ボタンの上には、画像ビュー(またはUIView)があります。

ここで、ユーザーが-上-左ボタンをタップしたとします。上記の画像/ビューは、その特定のコーナーで丸みを帯びている必要があります。

UIViewに丸みを帯びた角を適用するのに問題があります。

現在、次のコードを使用して、丸みを帯びた角を各ビューに適用しています。

    // imgVUserImg is a image view on IB.
    imgVUserImg.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"any Url Here"];
    CALayer *l = [imgVUserImg layer];
    [l setMasksToBounds:YES];
    [l setCornerRadius:5.0];  
    [l setBorderWidth:2.0];
    [l setBorderColor:[[UIColor darkGrayColor] CGColor]];

上記のコードは、提供されたビューの各コーナーに丸みを適用しています。代わりに、-上/上+左/下+右などの選択したコーナーに丸みを適用したかっただけです。

出来ますか?どのように?

4

14 に答える 14

358

iOS 3.2以降では、UIBezierPathsの機能を使用して、すぐに使用できる丸みを帯びた長方形を作成できます(指定した角のみが丸みを帯びています)。次に、これをのパスとしてCAShapeLayer使用し、これをビューのレイヤーのマスクとして使用できます。

// Create the path (with only the top-left corner rounded)
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds 
                                               byRoundingCorners:UIRectCornerTopLeft
                                                     cornerRadii:CGSizeMake(10.0, 10.0)];

// Create the shape layer and set its path
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = imageView.bounds;
maskLayer.path = maskPath.CGPath;

// Set the newly created shape layer as the mask for the image view's layer
imageView.layer.mask = maskLayer;

これで、Core Graphicsで図形を手動で定義したり、Photoshopでマスキング画像を作成したりする必要はありません。レイヤーを無効にする必要もありません。丸みを帯びた角を適用したり、新しい角に変更したりするのは、新しい角を定義し、それをマスクレイヤーのパスとしてUIBezierPath使用するのと同じくらい簡単です。CGPathメソッドのcornersパラメーターはbezierPathWithRoundedRect:byRoundingCorners:cornerRadii:ビットマスクであるため、複数のコーナーをOR演算することで丸めることができます。


編集:影を追加する

これに影を付けたい場合は、もう少し作業が必要です。

imageView.layer.mask = maskLayer」はマスクを適用するため、通常、影はマスクの外側には表示されません。秘訣は、透明なビューを使用してから、ビューのレイヤーに2つのサブレイヤー(s)を追加することCALayerです。どちらもを利用する必要があります。画像はのコンテンツとして追加されます。shadowLayerroundedLayerUIBezierPathroundedLayer

// Create a transparent view
UIView *theView = [[UIView alloc] initWithFrame:theFrame];
[theView setBackgroundColor:[UIColor clearColor]];

// Create the path (with only the top-left corner rounded)
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:theView.bounds 
                                               byRoundingCorners:UIRectCornerTopLeft
                                                     cornerRadii:CGSizeMake(10.0f, 10.0f)];

// Create the shadow layer
CAShapeLayer *shadowLayer = [CAShapeLayer layer];
[shadowLayer setFrame:theView.bounds];
[shadowLayer setMasksToBounds:NO];
[shadowLayer setShadowPath:maskPath.CGPath];
// ...
// Set the shadowColor, shadowOffset, shadowOpacity & shadowRadius as required
// ...

// Create the rounded layer, and mask it using the rounded mask layer
CALayer *roundedLayer = [CALayer layer];
[roundedLayer setFrame:theView.bounds];
[roundedLayer setContents:(id)theImage.CGImage];

CAShapeLayer *maskLayer = [CAShapeLayer layer];
[maskLayer setFrame:theView.bounds];
[maskLayer setPath:maskPath.CGPath];

roundedLayer.mask = maskLayer;

// Add these two layers as sublayers to the view
[theView.layer addSublayer:shadowLayer];
[theView.layer addSublayer:roundedLayer];
于 2011-04-29T00:48:12.910 に答える
45

iPhoneで丸い角のUILabelを作成するにはどうすればよいですか?そして、iPhoneで透明度のある丸みを帯びた長方形のビューはどのように行われますか?このコードを作成します。

次に、間違った質問に答えた(UIImageの代わりに丸みを帯びたUILabelを付けた)ことに気付いたので、このコードを使用して変更しました。

http://discussions.apple.com/thread.jspa?threadID=1683876

ビューテンプレートを使用してiPhoneプロジェクトを作成します。ビューコントローラで、これを追加します。

- (void)viewDidLoad
{
    CGRect rect = CGRectMake(10, 10, 200, 100);
    MyView *myView = [[MyView alloc] initWithFrame:rect];
    [self.view addSubview:myView];
    [super viewDidLoad];
}

MyView単なるUIImageViewサブクラスです:

@interface MyView : UIImageView
{
}

これまでグラフィックスコンテキストを使用したことはありませんでしたが、このコードをまとめることができました。2つのコーナーのコードがありません。コードを読むと、これをどのように実装したかがわかります(CGContextAddArc呼び出しの一部を削除し、コード内の半径値の一部を削除します。すべての角のコードがそこにあるので、それを開始点として使用し、必要のない角を作成するパーツ。必要に応じて、2つまたは3つの丸い角を持つ長方形を作成することもできます。

コードは完璧ではありませんが、少し整理できると思います。

static void addRoundedRectToPath(CGContextRef context, CGRect rect, float radius, int roundedCornerPosition)
{

    // all corners rounded
    //  CGContextMoveToPoint(context, rect.origin.x, rect.origin.y + radius);
    //  CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y + rect.size.height - radius);
    //  CGContextAddArc(context, rect.origin.x + radius, rect.origin.y + rect.size.height - radius, 
    //                  radius, M_PI / 4, M_PI / 2, 1);
    //  CGContextAddLineToPoint(context, rect.origin.x + rect.size.width - radius, 
    //                          rect.origin.y + rect.size.height);
    //  CGContextAddArc(context, rect.origin.x + rect.size.width - radius, 
    //                  rect.origin.y + rect.size.height - radius, radius, M_PI / 2, 0.0f, 1);
    //  CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y + radius);
    //  CGContextAddArc(context, rect.origin.x + rect.size.width - radius, rect.origin.y + radius, 
    //                  radius, 0.0f, -M_PI / 2, 1);
    //  CGContextAddLineToPoint(context, rect.origin.x + radius, rect.origin.y);
    //  CGContextAddArc(context, rect.origin.x + radius, rect.origin.y + radius, radius, 
    //                  -M_PI / 2, M_PI, 1);

    // top left
    if (roundedCornerPosition == 1) {
        CGContextMoveToPoint(context, rect.origin.x, rect.origin.y + radius);
        CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y + rect.size.height - radius);
        CGContextAddArc(context, rect.origin.x + radius, rect.origin.y + rect.size.height - radius, 
                        radius, M_PI / 4, M_PI / 2, 1);
        CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, 
                                rect.origin.y + rect.size.height);
        CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y);
        CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y);
    }   

    // bottom left
    if (roundedCornerPosition == 2) {
        CGContextMoveToPoint(context, rect.origin.x, rect.origin.y);
        CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y + rect.size.height);
        CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, 
                                rect.origin.y + rect.size.height);
        CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y);
        CGContextAddLineToPoint(context, rect.origin.x + radius, rect.origin.y);
        CGContextAddArc(context, rect.origin.x + radius, rect.origin.y + radius, radius, 
                        -M_PI / 2, M_PI, 1);
    }

    // add the other corners here


    CGContextClosePath(context);
    CGContextRestoreGState(context);
}


-(UIImage *)setImage
{
    UIImage *img = [UIImage imageNamed:@"my_image.png"];
    int w = img.size.width;
    int h = img.size.height;

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);

    CGContextBeginPath(context);
    CGRect rect = CGRectMake(0, 0, w, h);


    addRoundedRectToPath(context, rect, 50, 1);
    CGContextClosePath(context);
    CGContextClip(context);

    CGContextDrawImage(context, rect, img.CGImage);

    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    [img release];

    return [UIImage imageWithCGImage:imageMasked];
}

代替テキストhttp://nevan.net/skitch/skitched-20100224-092237.png

これを機能させるには、QuartzCoreフレームワークをそこに入れる必要があることを忘れないでください。

于 2010-02-23T14:59:44.513 に答える
18

私はこのコードをコードの多くの場所で使用しており、100%正しく機能します。1つのプロパティ「byRoundingCorners:UIRectCornerBottomLeft」を変更することで、任意のコーダーを変更できます。

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomLeft cornerRadii:CGSizeMake(10.0, 10.0)];

                CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
                maskLayer.frame = view.bounds;
                maskLayer.path = maskPath.CGPath;
                view.layer.mask = maskLayer;
                [maskLayer release];
于 2012-04-20T18:33:05.063 に答える
17

iOS 11では、一部のコーナーのみを丸めることができるようになりました

let view = UIView()

view.clipsToBounds = true
view.layer.cornerRadius = 8
view.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner]
于 2018-02-02T09:50:27.177 に答える
8

Swift3+構文を使用したCALayer拡張機能

extension CALayer {

    func round(roundedRect rect: CGRect, byRoundingCorners corners: UIRectCorner, cornerRadii: CGSize) -> Void {
        let bp = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: cornerRadii)
        let sl = CAShapeLayer()
        sl.frame = self.bounds
        sl.path = bp.cgPath
        self.mask = sl
    }
}

次のように使用できます。

let layer: CALayer = yourView.layer
layer.round(roundedRect: yourView.bounds, byRoundingCorners: [.bottomLeft, .topLeft], cornerRadii: CGSize(width: 5, height: 5))
于 2016-11-22T06:52:58.257 に答える
5

特定の角を丸めるためのスチュアートの例はうまく機能します。左上と右上のように複数の角を丸めたい場合は、これがその方法です

// Create the path (with only the top-left corner rounded)
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageview
                                               byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight
                                                     cornerRadii:CGSizeMake(10.0, 10.0)];

// Create the shape layer and set its path
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = imageview.bounds;
maskLayer.path = maskPath.CGPath;

// Set the newly created shape layer as the mask for the image view's layer
imageview.layer.mask = maskLayer; 
于 2013-11-11T12:43:45.500 に答える
5

共有していただきありがとうございます。ここでは、この問題の詳細について、swift2.0のソリューションを共有したいと思います。(UIRectCornerのプロトコルに準拠するため)

let mp = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.bottomLeft, .TopLeft], cornerRadii: CGSize(width: 10, height: 10))
let ml = CAShapeLayer()
ml.frame = self.bounds
ml.path = mp.CGPath
self.layer.mask = ml
于 2015-10-12T00:57:37.127 に答える
4

ニーズに応じて機能し、シャドウでも機能する、より簡単で高速な回答があります。スーパーレイヤーのmaskToBoundsをtrueに設定し、子レイヤーをオフセットして、それらのコーナーの2つがスーパーレイヤーの境界の外側になり、2つの側面の丸いコーナーを効果的に切り取ることができます。

もちろん、これは、同じ側に2つの丸い角だけを配置し、片側から数ピクセルを切り取ったときにレイヤーのコンテンツが同じように見える場合にのみ機能します。棒グラフを上面のみで丸める場合に最適です。

于 2012-09-04T11:34:20.443 に答える
3

この関連する質問を参照してください。CGPath角が丸いaに独自の長方形を描画し、を追加してCGPathから、CGContextを使用してそれにクリップする必要がありますCGContextClip

また、アルファ値を使用して丸みを帯びた長方形を画像に描画し、その画像を使用して、レイヤーのmaskプロパティとして設定した新しいレイヤーを作成することもできます(Appleのドキュメントを参照)。

于 2010-02-18T10:00:16.017 に答える
2

一部の角だけを丸めると、自動サイズ変更や自動レイアウトではうまく機能しません。

したがって、別のオプションは、通常を使用cornerRadiusして、別のビューの下またはスーパービューの境界の外側に不要なコーナーを非表示にして、コンテンツをクリップするように設定されていることを確認することです。

于 2015-05-21T12:38:23.260 に答える
2

半年遅れていますが、現在の人々のやり方は100%正しくないと思います。多くの人が、UIBezierPath + CAShapeLayerメソッドを使用すると、特にストーリーボードに設定されている場合に自動レイアウトが妨げられるという問題を抱えています。これ以上の答えはないので、自分で追加することにしました。

これを回避する非常に簡単な方法があります。関数に丸みを帯びた角を描画しdrawRect(rect: CGRect)ます。

たとえば、UIViewの上部を丸くしたい場合は、UIViewをサブクラス化し、適切な場所でそのサブクラスを使用します。

import UIKit

class TopRoundedView: UIView {

    override func drawRect(rect: CGRect) {
        super.drawRect(rect)

        var maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: UIRectCorner.TopLeft | UIRectCorner.TopRight, cornerRadii: CGSizeMake(5.0, 5.0))

        var maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.CGPath

        self.layer.mask = maskLayer
    }
}

これは問題を克服するための最良の方法であり、適応するのにまったく時間がかかりません。

于 2015-09-20T09:30:11.960 に答える
1

答え追加に追加するために、私UIViewはSwiftでシンプルで再利用可能なものを作成しました。ユースケースによっては、変更を加えることもできますが(すべてのレイアウトでオブジェクトを作成することは避けてください)、できるだけシンプルにしたいと思います。この拡張機能を使用すると、UIImageViewサブクラス化が気に入らない場合に、これを他のビュー(例)に簡単に適用できます。

extension UIView {

    func roundCorners(_ roundedCorners: UIRectCorner, toRadius radius: CGFloat) {
        roundCorners(roundedCorners, toRadii: CGSize(width: radius, height: radius))
    }

    func roundCorners(_ roundedCorners: UIRectCorner, toRadii cornerRadii: CGSize) {
        let maskBezierPath = UIBezierPath(
            roundedRect: bounds,
            byRoundingCorners: roundedCorners,
            cornerRadii: cornerRadii)
        let maskShapeLayer = CAShapeLayer()
        maskShapeLayer.frame = bounds
        maskShapeLayer.path = maskBezierPath.cgPath
        layer.mask = maskShapeLayer
    }
}

class RoundedCornerView: UIView {

    var roundedCorners: UIRectCorner = UIRectCorner.allCorners
    var roundedCornerRadii: CGSize = CGSize(width: 10.0, height: 10.0)

    override func layoutSubviews() {
        super.layoutSubviews()
        roundCorners(roundedCorners, toRadii: roundedCornerRadii)
    }
}

これをどのように適用するかを次に示しますUIViewController

class MyViewController: UIViewController {

    private var _view: RoundedCornerView {
        return view as! RoundedCornerView
    }

    override func loadView() {
        view = RoundedCornerView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        _view.roundedCorners = [.topLeft, .topRight]
        _view.roundedCornerRadii = CGSize(width: 10.0, height: 10.0)
    }
}
于 2017-03-27T14:17:56.770 に答える
0

スチュアートの答えをまとめると、次のように角を丸める方法があります。

@implementation UIView (RoundCorners)

- (void)applyRoundCorners:(UIRectCorner)corners radius:(CGFloat)radius {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;

    self.layer.mask = maskLayer;
}

@end

したがって、丸めコーナーを適用するには、次のようにします。

[self.imageView applyRoundCorners:UIRectCornerTopRight|UIRectCornerTopLeft radius:10];
于 2015-06-18T06:36:43.930 に答える
0

レイヤーのマスクを定義することをお勧めします。マスク自体はCAShapeLayer、専用パスを持つオブジェクトである必要があります。次のUIView拡張機能(Swift 4.2)を使用できます。

extension UIView {
    func round(corners: UIRectCorner, with radius: CGFloat) {
        let maskLayer = CAShapeLayer()
        maskLayer.frame = bounds
        maskLayer.path = UIBezierPath(
            roundedRect: bounds,
            byRoundingCorners: corners,
            cornerRadii: CGSize(width: radius, height: radius)
        ).cgPath
        layer.mask = maskLayer
   }
}
于 2018-10-31T16:10:56.633 に答える