web-dev-qa-db-fra.com

Comment donner une forme hexagonale à ImageView

Comment donner une forme hexagonale à ImageView. Est-il possible de faire de même? Si oui, alors comment. Si cela n'est pas possible, comment cela pourrait-il être réalisé?

<shape xmlns:Android="http//schemas.Android.com/apk/res/Android"
       Android:shape="hexagon">
  <solid Android:color="#ffffffff" />
  <size Android:width="60dp"
        Android:height="40dp" />
</shape>

Capture d'écran

enter image description here

Ici, je ne peux pas masquer l'image car je ne peux pas détecter la portion de bitmap à recadrer pour obtenir un bitmap de forme hexagonale. Je cherche donc la réponse pour donner une forme hexagonale à ImageView

28
N Sharma

Essayez cette vue. Vous pouvez l'ajuster pour vos besoins spécifiques, mais il dessine un masque hexagonal avec une bordure au-dessus d'une vue. La ressource d'arrière-plan passe sous le masque.

Le résultat:

enter image description here

Le code:

HexagonMaskView.Java

import Android.content.Context;
import Android.graphics.Canvas;
import Android.graphics.Color;
import Android.graphics.Path;
import Android.graphics.Region;
import Android.util.AttributeSet;
import Android.view.View;

public class HexagonMaskView extends View {
    private Path hexagonPath;
    private Path hexagonBorderPath;
    private float radius;
    private float width, height;
    private int maskColor;

public HexagonMaskView(Context context) {
    super(context);
    init();
}

public HexagonMaskView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public HexagonMaskView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
    hexagonPath = new Path();
    hexagonBorderPath = new Path();
    maskColor = 0xFF01FF77;
}

public void setRadius(float r) {
    this.radius = r;
    calculatePath();
}

public void setMaskColor(int color) {
    this.maskColor = color;
    invalidate();
}

private void calculatePath() {
    float triangleHeight = (float) (Math.sqrt(3) * radius / 2);
    float centerX = width/2;
    float centerY = height/2;
    hexagonPath.moveTo(centerX, centerY + radius);
    hexagonPath.lineTo(centerX - triangleHeight, centerY + radius/2);
    hexagonPath.lineTo(centerX - triangleHeight, centerY - radius/2);
    hexagonPath.lineTo(centerX, centerY - radius);
    hexagonPath.lineTo(centerX + triangleHeight, centerY - radius/2);
    hexagonPath.lineTo(centerX + triangleHeight, centerY + radius/2);
    hexagonPath.moveTo(centerX, centerY + radius);

    float radiusBorder = radius - 5;    
    float triangleBorderHeight = (float) (Math.sqrt(3) * radiusBorder / 2);
    hexagonBorderPath.moveTo(centerX, centerY + radiusBorder);
    hexagonBorderPath.lineTo(centerX - triangleBorderHeight, centerY + radiusBorder/2);
    hexagonBorderPath.lineTo(centerX - triangleBorderHeight, centerY - radiusBorder/2);
    hexagonBorderPath.lineTo(centerX, centerY - radiusBorder);
    hexagonBorderPath.lineTo(centerX + triangleBorderHeight, centerY - radiusBorder/2);
    hexagonBorderPath.lineTo(centerX + triangleBorderHeight, centerY + radiusBorder/2);
    hexagonBorderPath.moveTo(centerX, centerY + radiusBorder);
    invalidate();
}

@Override
public void onDraw(Canvas c){
    super.onDraw(c);
    c.clipPath(hexagonBorderPath, Region.Op.DIFFERENCE);
    c.drawColor(Color.WHITE);
    c.save();
    c.clipPath(hexagonPath, Region.Op.DIFFERENCE);
    c.drawColor(maskColor);
    c.save();
}

// getting the view size and default radius
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    width = MeasureSpec.getSize(widthMeasureSpec);
    height =  MeasureSpec.getSize(heightMeasureSpec);
    radius = height / 2 - 10;
    calculatePath();
}
}

Mise à jour 29.07.2016

Une meilleure façon de découper uniquement l'image source sans peindre l'arrière-plan de la vue entière. Basculé vers une ImageView en tant que classe de base pour bénéficier du scaleType. J'ai également fait du refactoring de code.

import Android.content.Context;
import Android.graphics.Canvas;
import Android.graphics.Color;
import Android.graphics.Paint;
import Android.graphics.Path;
import Android.graphics.PorterDuff;
import Android.graphics.Region;
import Android.util.AttributeSet;
import Android.widget.ImageView;

public class HexagonMaskView extends ImageView {
    private Path hexagonPath;
    private Path hexagonBorderPath;
    private Paint mBorderPaint;

    public HexagonMaskView(Context context) {
        super(context);
        init();
    }

    public HexagonMaskView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public HexagonMaskView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        this.hexagonPath = new Path();
        this.hexagonBorderPath = new Path();

        this.mBorderPaint = new Paint();
        this.mBorderPaint.setColor(Color.WHITE);
        this.mBorderPaint.setStrokeCap(Paint.Cap.ROUND);
        this.mBorderPaint.setStrokeWidth(50f);
        this.mBorderPaint.setStyle(Paint.Style.STROKE);
    }

    public void setRadius(float radius) {
        calculatePath(radius);
    }

    public void setBorderColor(int color) {
        this.mBorderPaint.setColor(color);
        invalidate();
    }

    private void calculatePath(float radius) {
        float halfRadius = radius / 2f;
        float triangleHeight = (float) (Math.sqrt(3.0) * halfRadius);
        float centerX = getMeasuredWidth() / 2f;
        float centerY = getMeasuredHeight() / 2f;

        this.hexagonPath.reset();
        this.hexagonPath.moveTo(centerX, centerY + radius);
        this.hexagonPath.lineTo(centerX - triangleHeight, centerY + halfRadius);
        this.hexagonPath.lineTo(centerX - triangleHeight, centerY - halfRadius);
        this.hexagonPath.lineTo(centerX, centerY - radius);
        this.hexagonPath.lineTo(centerX + triangleHeight, centerY - halfRadius);
        this.hexagonPath.lineTo(centerX + triangleHeight, centerY + halfRadius);
        this.hexagonPath.close();

        float radiusBorder = radius - 5f;
        float halfRadiusBorder = radiusBorder / 2f;
        float triangleBorderHeight = (float) (Math.sqrt(3.0) * halfRadiusBorder);

        this.hexagonBorderPath.reset();
        this.hexagonBorderPath.moveTo(centerX, centerY + radiusBorder);
        this.hexagonBorderPath.lineTo(centerX - triangleBorderHeight, centerY + halfRadiusBorder);
        this.hexagonBorderPath.lineTo(centerX - triangleBorderHeight, centerY - halfRadiusBorder);
        this.hexagonBorderPath.lineTo(centerX, centerY - radiusBorder);
        this.hexagonBorderPath.lineTo(centerX + triangleBorderHeight, centerY - halfRadiusBorder);
        this.hexagonBorderPath.lineTo(centerX + triangleBorderHeight, centerY + halfRadiusBorder);
        this.hexagonBorderPath.close();
        invalidate();
    }

    @Override
    public void onDraw(Canvas c) {
        c.drawPath(hexagonBorderPath, mBorderPaint);
        c.clipPath(hexagonPath, Region.Op.INTERSECT);
        c.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        super.onDraw(c);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(width, height);
        calculatePath(Math.min(width / 2f, height / 2f) - 10f);
    }
}

Exemple de disposition:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:paddingBottom="@dimen/activity_vertical_margin"
    Android:paddingLeft="@dimen/activity_horizontal_margin"
    Android:paddingRight="@dimen/activity_horizontal_margin"
    Android:paddingTop="@dimen/activity_vertical_margin"
    Android:background="@Android:color/holo_green_dark">

    <com.scelus.hexagonmaskimproved.HexagonMaskView
        Android:id="@+id/image"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        Android:src="@drawable/bear"
        Android:background="@Android:color/holo_green_light"/>

</RelativeLayout>

New result

60
SceLus

Voici mon code de travail pour cela, il prend en charge les ombres pour:

import Android.annotation.SuppressLint;
import Android.content.Context;
import Android.graphics.Bitmap;
import Android.graphics.BitmapShader;
import Android.graphics.Canvas;
import Android.graphics.Color;
import Android.graphics.Paint;
import Android.graphics.Path;
import Android.graphics.PorterDuff;
import Android.graphics.Shader;
import Android.graphics.drawable.BitmapDrawable;
import Android.util.AttributeSet;
import Android.widget.ImageView;

public class HexagonImageView extends ImageView {

    private Path hexagonPath;
    private Path hexagonBorderPath;
    private float radius;
    private Bitmap image;
    private int viewWidth;
    private int viewHeight;
    private Paint paint;
    private BitmapShader shader;
    private Paint paintBorder;
    private int borderWidth = 4;

    public HexagonImageView(Context context) {
        super(context);
        setup();
    }

    public HexagonImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setup();
    }

    public HexagonImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setup();
    }

    private void setup() {
        Paint = new Paint();
        Paint.setAntiAlias(true);

        paintBorder = new Paint();
        setBorderColor(Color.WHITE);
        paintBorder.setAntiAlias(true);
        this.setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
        paintBorder.setShadowLayer(4.0f, 1.0f, 1.0f, Color.BLACK);

        hexagonPath = new Path();
        hexagonBorderPath = new Path();
    }

    public void setRadius(float r) {
        this.radius = r;
        calculatePath();
    }

    public void setBorderWidth(int borderWidth)  {
        this.borderWidth = borderWidth;
        this.invalidate();
    }

    public void setBorderColor(int borderColor)  {
        if (paintBorder != null)
            paintBorder.setColor(borderColor);

        this.invalidate();
    }

    private void calculatePath() {

        float triangleHeight = (float) (Math.sqrt(3) * radius / 2);
        float centerX = viewWidth/2;
        float centerY = viewHeight/2;

        hexagonBorderPath.moveTo(centerX, centerY + radius);
        hexagonBorderPath.lineTo(centerX - triangleHeight, centerY + radius/2);
        hexagonBorderPath.lineTo(centerX - triangleHeight, centerY - radius/2);
        hexagonBorderPath.lineTo(centerX, centerY - radius);
        hexagonBorderPath.lineTo(centerX + triangleHeight, centerY - radius/2);
        hexagonBorderPath.lineTo(centerX + triangleHeight, centerY + radius/2);
        hexagonBorderPath.moveTo(centerX, centerY + radius);

        float radiusBorder = radius - borderWidth;    
        float triangleBorderHeight = (float) (Math.sqrt(3) * radiusBorder / 2);

        hexagonPath.moveTo(centerX, centerY + radiusBorder);
        hexagonPath.lineTo(centerX - triangleBorderHeight, centerY + radiusBorder/2);
        hexagonPath.lineTo(centerX - triangleBorderHeight, centerY - radiusBorder/2);
        hexagonPath.lineTo(centerX, centerY - radiusBorder);
        hexagonPath.lineTo(centerX + triangleBorderHeight, centerY - radiusBorder/2);
        hexagonPath.lineTo(centerX + triangleBorderHeight, centerY + radiusBorder/2);
        hexagonPath.moveTo(centerX, centerY + radiusBorder);

        invalidate();
    }

    private void loadBitmap()  {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();

        if (bitmapDrawable != null)
            image = bitmapDrawable.getBitmap();
    }

    @SuppressLint("DrawAllocation")
    @Override
    public void onDraw(Canvas canvas){
        super.onDraw(canvas);

        loadBitmap();

        // init shader
        if (image != null) {

            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);

            shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            Paint.setShader(shader);

            canvas.drawPath(hexagonBorderPath, paintBorder);
            canvas.drawPath(hexagonPath, Paint);
        }

    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec, widthMeasureSpec);

        viewWidth = width - (borderWidth * 2);
        viewHeight = height - (borderWidth * 2);

        radius = height / 2 - borderWidth;

        calculatePath();

        setMeasuredDimension(width, height);
    }

    private int measureWidth(int measureSpec)   {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY)  {
            result = specSize;
        }
        else {
            result = viewWidth;
        }

        return result;
    }

    private int measureHeight(int measureSpecHeight, int measureSpecWidth)  {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpecHeight);
        int specSize = MeasureSpec.getSize(measureSpecHeight);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        }
        else {
            result = viewHeight;
        }

        return (result + 2);
    }


}
7
lacas

Il y a quelques choses que vous pouvez essayer:

  • Vous voudrez peut-être essayer de dessiner un 9patch en haut de votre image.

  • Il y a aussi ce petit tuto de Romain Guy: http://www.curious-creature.org/2012/12/11/11Android-recipe-1-image-with-rounded-corners/

    BitmapShader shader;
    shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
    
    Paint paint = new Paint();
    Paint.setAntiAlias(true);
    Paint.setShader(shader);
    
    RectF rect = new RectF(0.0f, 0.0f, width, height);
    
    // rect contains the bounds of the shape
    // radius is the radius in pixels of the rounded corners
    // Paint contains the shader that will texture the shape
    canvas.drawRoundRect(rect, radius, radius, Paint);
    

    Au lieu d'utiliser la méthode drawRoundRect() du canevas, vous pouvez essayer d'utiliser drawPath() pour obtenir la forme souhaitée.

    J'espère que cela vous met dans la bonne direction.

4
Spartako

Voir cet exemple qui crée un triangle afin que vous puissiez en tirer une logique :)

http://looksok.wordpress.com/2013/08/24/Android-triangle-arrow-defined-as-an-xml-shape/

Une autre solution que j'ai trouvée mais non testée alors essayez aussi

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView tv = (TextView) findViewById(R.id.text);

    Path path = new Path();
    float stdW = 100;
    float stdH = 100;
    float w3 = stdW / 3;
    float h2 = stdH / 2;
    path.moveTo(0, h2);
    h2 -= 6 / 2;
    path.rLineTo(w3, -h2);         path.rLineTo(w3, 0); path.rLineTo(w3, h2);
    path.rLineTo(-w3, h2); path.rLineTo(-w3, 0); path.rLineTo(-w3, -h2);
    Shape s = new PathShape(path, stdW, stdH);
    ShapeDrawable d = new ShapeDrawable(s);
    Paint p = d.getPaint();
    p.setColor(0xffeeeeee);
    p.setStyle(Style.STROKE);
    p.setStrokeWidth(6);

    tv.setBackgroundDrawable(d);
} 

Source: groupe Google

Troisième solution - Cela pourrait être une bibliothèque utile

PathDrawable est un Drawable qui dessine des formes simples en utilisant l'objet Path.

4
MilapTank

Il est tard pour répondre .. Mais j'espère que cela aidera quelqu'un ...

  public Bitmap getHexagonShape(Bitmap scaleBitmapImage) {
    // TODO Auto-generated method stub
    int targetWidth = 200;
    int targetHeight =200;
    Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, 
            targetHeight,Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(targetBitmap);

    Path path = new Path();
    float stdW = 200;
    float stdH = 200;
    float w3 =stdW / 2;
    float h2 = stdH / 2;


    float radius=stdH/2-10;
    float triangleHeight = (float) (Math.sqrt(3) * radius / 2);
      float centerX = stdW/2;
      float centerY = stdH/2;
      path.moveTo(centerX, centerY + radius);
      path.lineTo(centerX - triangleHeight, centerY + radius/2);
      path.lineTo(centerX - triangleHeight, centerY - radius/2);
      path.lineTo(centerX, centerY - radius);
      path.lineTo(centerX + triangleHeight, centerY - radius/2);
      path.lineTo(centerX + triangleHeight, centerY + radius/2);
      path.moveTo(centerX, centerY + radius);


    canvas.clipPath(path);
    Bitmap sourceBitmap = scaleBitmapImage;
    canvas.drawBitmap(sourceBitmap, 
            new Rect(0, 0, sourceBitmap.getWidth(),
                    sourceBitmap.getHeight()), 
                    new Rect(0, 0, targetWidth,
                            targetHeight), null);
    return targetBitmap;
}




public static Bitmap drawableToBitmap (Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable)drawable).getBitmap();
    }

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

Appelez cela où vous voulez utiliser

    Drawable drawable = getResources().getDrawable( R.drawable.placeholder );        
    Bitmap b=getHexagonShape(drawableToBitmap(drawable));
    img=(ImageView)findViewById(R.id.imageView);

    img.setImageBitmap(b);
3
ADT

Je l'ai résolu en utilisant ce code:

    private Bitmap getHexagoneCroppedBitmap(Bitmap bitmap, int radius) {
        Bitmap finalBitmap;
        if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
               finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                            false);
        else
               finalBitmap = bitmap;
        Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                     finalBitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                     finalBitmap.getHeight());

        Point point1_draw = new Point(75, 0);
        Point point2_draw = new Point(0, 50);
        Point point3_draw = new Point(0, 100);
        Point point4_draw = new Point(75, 150);
        Point point5_draw = new Point(150, 100);
        Point point6_draw = new Point(150, 50);

        Path path = new Path();
        path.moveTo(point1_draw.x, point1_draw.y);
        path.lineTo(point2_draw.x, point2_draw.y);
        path.lineTo(point3_draw.x, point3_draw.y);
        path.lineTo(point4_draw.x, point4_draw.y);
        path.lineTo(point5_draw.x, point5_draw.y);
        path.lineTo(point6_draw.x, point6_draw.y);

        path.close();
        canvas.drawARGB(0, 0, 0, 0);
        Paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawPath(path, Paint);
        Paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(finalBitmap, rect, rect, Paint);

        return output;
    }
1
Aj 27

Je ne sais pas si le PO a obtenu la réponse qu'il cherchait, mais voilà.

J'ai créé une vue personnalisée, qui étend ImageView, qui fera un peu mieux le travail pour vous. La réponse ici crée simplement un maks à l'intérieur de l'ImageView et vous oblige à définir l'image comme arrière-plan

Ma vue vous permet de définir l'image comme un bitmap standard, elle gère CenterCrop et la mise à l'échelle de l'image. En fait, il définit le masque à l'extérieur et avec la même bordure et l'ombre portée.

Et si cela ne suffit pas, vous pouvez facilement créer des formes personnalisées à restituer, en étendant simplement la classe RenderShape. (4 formes sont incluses dans la bibliothèque: Circle, Triangle, Hexagon et Octagon)

Jetez un oeil sur mon github

À votre santé

La fonction ci-dessous lit votre image comme bitmap d'entrée et retourne un bitmap de forme hexagonale

public Bitmap getHexagonShape(Bitmap scaleBitmapImage) {
      // TODO Auto-generated method stub
      int targetWidth = 600;
      int targetHeight = 600;
      Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, 
                                targetHeight,Bitmap.Config.ARGB_8888);

                    Canvas canvas = new Canvas(targetBitmap);

      Path path = new Path();
        float stdW = 300;
        float stdH = 300;
        float w3 =stdW / 2;
        float h2 = stdH / 2;
        path.moveTo(0, (float) (h2*Math.sqrt(3)/2));
        path.rLineTo(w3/2, -(float) (h2*Math.sqrt(3)/2)); path.rLineTo(w3, 0);   path.rLineTo(w3/2, (float) (h2*Math.sqrt(3)/2));
        path.rLineTo(-w3/2, (float) (h2*Math.sqrt(3)/2)); path.rLineTo(-w3, 0); path.rLineTo(-w3/2, -(float) (h2*Math.sqrt(3)/2));


                    canvas.clipPath(path);
      Bitmap sourceBitmap = scaleBitmapImage;
      canvas.drawBitmap(sourceBitmap, 
                                    new Rect(0, 0, sourceBitmap.getWidth(),
        sourceBitmap.getHeight()), 
                                    new Rect(0, 0, targetWidth,
        targetHeight), null);
      return targetBitmap;
     }
1
uzair_syed

Vous pouvez utiliser le Android Shape ImageView by siamed.

https://github.com/siyamed/Android-shape-imageview

<com.github.siyamed.shapeimageview.HexagonImageView
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:layout_margin="8dp"
    Android:src="@drawable/neo"
    app:siBorderWidth="8dp"
    app:siBorderColor="@color/darkgray"/>

Veuillez lire la documentation sur github, de nombreuses options sont disponibles.

1
Binoy Babu