如何在Java中制作星形?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16327588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:19:38  来源:igfitidea点击:

How to make star shape in Java?

javaswingpaintcomponentshapes

提问by Mina Hafzalla

I'm trying to make some shapes with Java. I created two rectangles with two different colors but I want to create a star shape and I can't find useful source to help me doing this.

我正在尝试用 Java 制作一些形状。我创建了两个具有两种不同颜色的矩形,但我想创建一个星形,但找不到有用的资源来帮助我做到这一点。

Here is my code:

这是我的代码:

import java.awt.*;
import javax.swing.*;

public class shapes extends JPanel{

    @Override
    public void paintComponent(Graphics GPHCS){
        super.paintComponent(GPHCS);

        GPHCS.setColor(Color.BLUE);
        GPHCS.fillRect(25,25,100,30);

        GPHCS.setColor(Color.GRAY);
        GPHCS.fillRect(25,65,100,30);

        GPHCS.setColor(new Color(190,81,215));
        GPHCS.drawString("This is my text", 25, 120);
    }
}

采纳答案by Héctor van den Boorn

You could try using a polygon and some basic math:

您可以尝试使用多边形和一些基本数学:

    int midX = 500;
    int midY = 340;
    int radius[] = {118,40,90,40};
    int nPoints = 16;
    int[] X = new int[nPoints];
    int[] Y = new int[nPoints];

    for (double current=0.0; current<nPoints; current++)
    {
        int i = (int) current;
        double x = Math.cos(current*((2*Math.PI)/max))*radius[i % 4];
        double y = Math.sin(current*((2*Math.PI)/max))*radius[i % 4];

        X[i] = (int) x+midX;
        Y[i] = (int) y+midY;
    }

    g.setColor(Color.WHITE);
    g.fillPolygon(X, Y, nPoints);

回答by StanislavL

You can also use existing classes e.g. http://java-sl.com/shapes.htmlfor regular polygons and stars.

您还可以使用现有的类,例如http://java-sl.com/shapes.html用于正多边形和星形。

回答by Marco13

The Polygonclass can be considered as a legacy class that has been there since Java 1.0, but should hardly be used any more in new code. The odd way of specifying the x/y coordinates in separate arrays, and, more importantly, the fact that it only supports int[]arrays limits its application areas. Although it implements the Shapeinterface, there are more modern implementations of this interface that can be used to represent polygons. In most cases, describing the polygon as a Path2Dis easier and more flexible. One can create a Path2D p = new Path2D.Double();and then do a sequence of moveToand lineTocalls to geneate the desired shape.

Polygon班可被视为一个传统类,一直以来存在的Java 1.0,但应该很难在新的代码中使用了。在单独的数组中指定 x/y 坐标的奇怪方式,更重要的是,它只支持int[]数组的事实限制了它的应用领域。尽管它实现了该Shape接口,但该接口还有更多现代实现可用于表示多边形。在大多数情况下,将多边形描述为 aPath2D更容易也更灵活。可以创建 aPath2D p = new Path2D.Double();然后执行一系列moveTolineTo调用以生成所需的形状。

The following program shows how the Path2Dclass may be used to generate star shapes. The most important method is the createStarmethod. It is very generic. It receives

以下程序显示了如何使用Path2D该类生成星形。最重要的方法是createStar方法。这是非常通用的。它接收

  • the center coordinates for the star
  • the inner and outer radius of the star
  • the number of rays that the star should have
  • the angle where the first ray should be (i.e. the rotation angle of the star)
  • 恒星的中心坐标
  • 恒星的内半径和外半径
  • 恒星应具有的射线数
  • 第一条射线应该在的角度(即恒星的旋转角度)

If desired, a simpler method may be wrapped around this one - as with the createDefaultStarexample in the code below.

如果需要,可以围绕此方法使用更简单的方法 - 就像createDefaultStar下面代码中的示例一样。

The program shows different stars, painted as lines and filled with different colors and radial gradient paints, as examples:

该程序显示不同的星星,绘制为线条并填充不同的颜色和径向渐变涂料,例如:

Stars

星星

The complete program as a MCVE:

作为MCVE的完整程序:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RadialGradientPaint;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Path2D;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class DrawStarShape
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new DrawStarShapePanel());
        f.setSize(600, 600);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

}

class DrawStarShapePanel extends JPanel
{
    @Override
    protected void paintComponent(Graphics gr)
    {
        super.paintComponent(gr);
        Graphics2D g = (Graphics2D) gr;
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);

        g.setColor(Color.BLACK);
        g.draw(createDefaultStar(50, 200, 200));

        g.setPaint(Color.RED);
        g.fill(createStar(400, 400, 40, 60, 10, 0));

        g.setPaint(new RadialGradientPaint(
            new Point(400, 200), 60, new float[] { 0, 1 }, 
            new Color[] { Color.RED, Color.YELLOW }));
        g.fill(createStar(400, 200, 20, 60, 8, 0));

        g.setPaint(new RadialGradientPaint(
            new Point(200, 400), 50, new float[] { 0, 0.3f, 1 }, 
            new Color[] { Color.RED, Color.YELLOW, Color.ORANGE }));
        g.fill(createStar(200, 400, 40, 50, 20, 0));

    }

    private static Shape createDefaultStar(double radius, double centerX,
        double centerY)
    {
        return createStar(centerX, centerY, radius, radius * 2.63, 5,
            Math.toRadians(-18));
    }

    private static Shape createStar(double centerX, double centerY,
        double innerRadius, double outerRadius, int numRays,
        double startAngleRad)
    {
        Path2D path = new Path2D.Double();
        double deltaAngleRad = Math.PI / numRays;
        for (int i = 0; i < numRays * 2; i++)
        {
            double angleRad = startAngleRad + i * deltaAngleRad;
            double ca = Math.cos(angleRad);
            double sa = Math.sin(angleRad);
            double relX = ca;
            double relY = sa;
            if ((i & 1) == 0)
            {
                relX *= outerRadius;
                relY *= outerRadius;
            }
            else
            {
                relX *= innerRadius;
                relY *= innerRadius;
            }
            if (i == 0)
            {
                path.moveTo(centerX + relX, centerY + relY);
            }
            else
            {
                path.lineTo(centerX + relX, centerY + relY);
            }
        }
        path.closePath();
        return path;
    }
}

回答by Ali Bagheri

I have 2 method.

我有2个方法。

1)

1)

public static Bitmap drawStar(int W, int H, int color, boolean andRing)
{
    Path path = new Path();
    Bitmap output = Bitmap.createBitmap(W, H, Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(color);

    float midW ,min ,fat ,half ,radius;

    if(andRing)
    {
        midW = W / 2;
        min = Math.min(W, H);
        half = min / 2;
        midW = midW - half;

        fat = min / 17;
        radius = half - fat;

        paint.setStrokeWidth(fat);
        paint.setStyle(Paint.Style.STROKE);
        canvas.drawCircle(midW + half, half, radius, paint);

        path.reset();
        paint.setStyle(Paint.Style.FILL);
        path.moveTo( half * 0.5f, half * 0.84f);
        path.lineTo( half * 1.5f, half * 0.84f);
        path.lineTo( half * 0.68f, half * 1.45f);
        path.lineTo( half * 1.0f, half * 0.5f);
        path.lineTo( half * 1.32f, half * 1.45f);
        path.lineTo( half * 0.5f, half * 0.84f);
    }
    else
    {
        min = Math.min(W, H);
        half = min/2;

        path.reset();
        paint.setStyle(Paint.Style.FILL);

        path.moveTo( half * 0.1f  , half * 0.65f);
        path.lineTo( half * 1.9f  , half * 0.65f);
        path.lineTo( half * 0.40f , half * 1.65f);
        path.lineTo( half       , 0           );
        path.lineTo( half * 1.60f, half * 1.65f);
        path.lineTo( half * 0.1f, half * 0.65f);
    }

    canvas.drawPath(path, paint);

    return output;
}

2)

2)

  public static Bitmap drawStar(int W,int H,int spikes,int innerRadius,int outerRadius, int backColor,boolean border, int borderColor)
{
    if(W < 10)
        W = 10;

    if(H < 10)
        H = 10;

    if(spikes < 5)
        spikes = 5;

    int smallL = W;

    if(H < W)
        smallL = H;

    if(outerRadius > smallL/2)
        outerRadius = smallL/2;

    if(innerRadius < 5)
        innerRadius = 5;

    if(border)
    {
        outerRadius -=2;
        innerRadius -=2;
    }

    Path path = new Path();
    Bitmap output = Bitmap.createBitmap(W, H, Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(backColor);
    int cx = W/2;
    int cy = H/2;

    double rot = Math.PI / 2 * 3;
    float x,y;
    double step = Math.PI / spikes;

    path.moveTo(cx, cy - outerRadius);

    for (int i = 0; i < spikes; i++)
    {
        x = (float) (cx + Math.cos(rot) * outerRadius);
        y = (float) (cy + Math.sin(rot) * outerRadius);
        path.lineTo(x, y);
        rot += step;

        x = (float) (cx + Math.cos(rot) * innerRadius);
        y = (float) (cy + Math.sin(rot) * innerRadius);
        path.lineTo(x, y);
        rot += step;
    }

    path.lineTo(cx, cy - outerRadius);
    path.close();

    canvas.drawPath(path, paint);

    if(border)
    {
        paint.setStyle(Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setColor(borderColor);
        canvas.drawPath(path, paint);
    }
    return output;
}