AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / user-849123

Erhan Demirci's questions

Martin Hope
Erhan Demirci
Asked: 2023-08-17 18:30:40 +0800 CST

obtenha o UIBezierPath da imagem sem área transparente

  • 5

Eu tenho uma imagem transparente com a forma como esta. Podemos extrair o UIBezierPathdesta imagem? Por exemplo, eu mesmo posso desenhar um hexágono em minha UIViewaula, mas não consegui entender UIBezierPathessa forma.

insira a descrição da imagem aqui

Imagem original:orjinalImage

class FreeShapeView: UIView {
    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        context?.clear(rect)
      
        context?.setAllowsAntialiasing(true)
        context?.setShouldAntialias(true)
        context?.setLineJoin(CGLineJoin.round)
        
        let edge: CGFloat = 5.9/2

        let path: UIBezierPath = UIBezierPath()
        
        path.move(to: CGPoint(x: rect.width/2, y: edge))
        path.addLine(to: CGPoint(x: rect.width - edge, y: rect.height/3))
        path.addLine(to: CGPoint(x: rect.width - edge, y: rect.height/3*2))
        path.addLine(to: CGPoint(x: rect.width/2, y: rect.height - edge))
        path.addLine(to: CGPoint(x: edge, y: rect.height/3*2))
        path.addLine(to: CGPoint(x: edge, y: rect.height/3))
        
        path.close()
        context?.addPath(path.cgPath)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        backgroundColor = .clear
    }
}

Meu código Objective C para OpenCV

      + (UIBezierPath *)removeTransparentAreaAndFindContours:(UIImage *)image {
    // Convert UIImage to cv::Mat
   
    cv::Mat cvImage = [self cvMatFromUIImage:image];


    // Convert image to grayscale
    cv::Mat grayscaleImage;
    cv::cvtColor(cvImage, grayscaleImage, cv::COLOR_RGBA2GRAY);

    // Apply threshold to create binary image
    cv::Mat binaryImage;
    cv::threshold(grayscaleImage, binaryImage, 1, 255, cv::THRESH_BINARY);

    // Find contours
    std::vector<std::vector<cv::Point>> contours;
    std::vector<cv::Vec4i> hierarchy;
    cv::findContours(binaryImage, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);

    // Create a UIBezierPath from the contours
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    for (size_t i = 0; i < contours.size(); i++) {
        const std::vector<cv::Point> &contour = contours[i];
        for (size_t j = 0; j < contour.size(); j++) {
            const cv::Point &point = contour[j];
            CGPoint cgPoint = CGPointMake(point.x, point.y);
            if (j == 0) {
                [bezierPath moveToPoint:cgPoint];
            } else {
                [bezierPath addLineToPoint:cgPoint];
            }
        }
        [bezierPath closePath];
    }

    return bezierPath;
}

+ (cv::Mat)cvMatFromUIImage:(UIImage *)image {
    CGColorSpaceRef colorSpace = CGImageGetColorSpace(image.CGImage);
    CGFloat cols = image.size.width;
    CGFloat rows = image.size.height;
    cv::Mat cvMat(rows, cols, CV_8UC4); // 8 bits per channel, 4 channels (RGBA)

    CGContextRef contextRef = CGBitmapContextCreate(cvMat.data, cols, rows, 8, cvMat.step[0], colorSpace, kCGImageAlphaNoneSkipLast | kCGBitmapByteOrderDefault);
    CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows), image.CGImage);
    CGContextRelease(contextRef);

    return cvMat;
}

Eu recebo algum resultado como este.

Element 1: Type = MoveToPoint, Points = (0.0, 0.0) (6.9370081173396e-310, 0.0) 
Element 2: Type = AddLineToPoint, Points = (0.0, 794.0) (6.9370081173396e-310, 0.0) 
Element 3: Type = AddLineToPoint, Points = (619.0, 794.0) (6.9370081173396e-310, 0.0) 
Element 4: Type = AddLineToPoint, Points = (620.0, 795.0) (6.9370081173396e-310, 0.0) 
Element 5: Type = AddLineToPoint, Points = (620.0, 1270.0) (6.9370081173396e-310, 0.0) 
Element 6: Type = AddLineToPoint, Points = (1998.0, 1270.0) (6.9370081173396e-310, 0.0) 
Element 7: Type = AddLineToPoint, Points = (1998.0, 0.0) (6.9370081173396e-310, 0.0) 
Element 8: Type = CloseSubpath, Points = (1998.0, 0.0) (6.9370081173396e-310, 0.0) 

código de teste é:

 path = UIBezierPath()
        
        path.move(to: CGPoint(x: 0.0, y: 0.0))
        path.addLine(to: CGPoint(x:0.0 , y:794.0 ))
        path.addLine(to: CGPoint(x:619.0 , y:794.0 ))
        path.addLine(to: CGPoint(x: 620.0, y: 795.0 ))
        path.addLine(to: CGPoint(x:620.0 , y:1270.0 ))
        path.addLine(to: CGPoint(x: 1998.0, y:1270.0 ))
        path.addLine(to: CGPoint(x:1998.0 , y: 0.0))
        
        path.close()
        context?.addPath(path.cgPath)

mas é desenhado assim:

insira a descrição da imagem aqui

O que estou fazendo de errado ? obrigado

ios
  • 1 respostas
  • 53 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve